repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/singleton/partition/PartitionServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.singleton.partition;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jgroups.Address;
import org.jgroups.Event;
import org.jgroups.JChannel;
import org.jgroups.View;
import org.jgroups.protocols.DISCARD;
import org.jgroups.protocols.TP;
import org.jgroups.protocols.pbcast.GMS;
import org.jgroups.stack.ProtocolStack;
/**
* Servlet used to simulate network partitions. Responds to {@code /partition?partition=true} by inserting DISCARD protocol to the stack
* and installing new view directly on the {@link GMS} and responds to {@code /partition?partition=false} by removing previously inserted
* {@link DISCARD} protocol and passing MERGE event up the stack.
* <p>
* Note that while it would be desirable for the tests to leave splitting and merging to the servers themselves, this is not practical in a
* test suite. While FD/VERIFY_SUSPECT/GMS can be be configured to detect partitions quickly the MERGE3 handles merges within randomized
* intervals and uses unreliable channel which can easily take several minutes for merge to actually happen. Also, speeds up the test
* significantly.
*
* @author Radoslav Husar
*/
@WebServlet(urlPatterns = {PartitionServlet.PARTITION})
public class PartitionServlet extends HttpServlet {
private static final long serialVersionUID = 3034138469210308974L;
private static final long VIEWS_TIMEOUT = 3_000;
public static final String PARTITION = "partition";
private static Map<Address, View> mergeViews;
public static URI createURI(URL baseURL, boolean partition) throws URISyntaxException {
return baseURL.toURI().resolve(PARTITION + '?' + PARTITION + '=' + partition);
}
@Resource(lookup = "java:jboss/jgroups/channel/default")
private JChannel channel;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
boolean partition = Boolean.valueOf(request.getParameter(PARTITION));
this.log("Simulating network partitions? " + partition);
try {
if (partition) {
// Store views for future merge event
GMS gms = this.channel.getProtocolStack().findProtocol(GMS.class);
mergeViews = new HashMap<>();
this.channel.getView().getMembers().forEach(
address -> mergeViews.put(address, View.create(address, gms.getViewId().getId() + 1, address))
);
// Wait a few seconds to ensure everyone stored a full view
Thread.sleep(VIEWS_TIMEOUT);
// Simulate partitions by injecting DISCARD protocol
DISCARD discard = new DISCARD();
discard.discardAll(true);
this.channel.getProtocolStack().insertProtocol(discard, ProtocolStack.Position.ABOVE, TP.class);
// Speed up partitioning
View view = View.create(this.channel.getAddress(), gms.getViewId().getId() + 1, this.channel.getAddress());
gms.installView(view);
} else {
this.channel.getProtocolStack().removeProtocol(DISCARD.class);
// Wait a few seconds for the other node to remove DISCARD so it does not discard our MERGE request
Thread.sleep(VIEWS_TIMEOUT);
// Since the coordinator is determined by ordering the address in org.jgroups.protocols.pbcast.Merger#determineMergeLeader
// let just all nodes send the merge..
this.log("Passing event up the stack: " + new Event(Event.MERGE, mergeViews));
GMS gms = this.channel.getProtocolStack().findProtocol(GMS.class);
gms.up(new Event(Event.MERGE, mergeViews));
mergeViews = null;
}
response.getWriter().write("Success");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
throw new ServletException(e);
}
}
}
| 5,497
| 43.699187
| 139
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/singleton/partition/SingletonServiceActivator.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.singleton.partition;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.NODE_1;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.NODE_2;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jboss.as.clustering.controller.ServiceValueCaptorServiceConfigurator;
import org.jboss.as.test.clustering.cluster.singleton.service.NodeServiceExecutorRegistry;
import org.jboss.as.test.clustering.cluster.singleton.service.SingletonElectionListenerService;
import org.jboss.msc.service.ServiceActivator;
import org.jboss.msc.service.ServiceActivatorContext;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.wildfly.clustering.service.ChildTargetService;
import org.wildfly.clustering.singleton.SingletonDefaultCacheRequirement;
import org.wildfly.clustering.singleton.election.NamePreference;
import org.wildfly.clustering.singleton.election.PreferredSingletonElectionPolicy;
import org.wildfly.clustering.singleton.election.SimpleSingletonElectionPolicy;
import org.wildfly.clustering.singleton.service.SingletonServiceConfiguratorFactory;
/**
* @author Tomas Hofman
*/
public class SingletonServiceActivator implements ServiceActivator {
private static final String CONTAINER_NAME = "server";
public static final ServiceName SERVICE_A_NAME = ServiceName.JBOSS.append("test1", "service", "default");
public static final ServiceName SERVICE_B_NAME = ServiceName.JBOSS.append("test2", "service", "default");
public static final String SERVICE_A_PREFERRED_NODE = NODE_2;
public static final String SERVICE_B_PREFERRED_NODE = NODE_1;
@Override
public void activate(ServiceActivatorContext context) {
ServiceBuilder<?> builder = context.getServiceTarget().addService(ServiceName.JBOSS.append("test1", "service", "installer"));
Supplier<SingletonServiceConfiguratorFactory> factoryDependency = builder.requires(ServiceName.parse(SingletonDefaultCacheRequirement.SINGLETON_SERVICE_CONFIGURATOR_FACTORY.resolve(CONTAINER_NAME)));
Consumer<ServiceTarget> installer = target -> {
SingletonServiceConfiguratorFactory factory = factoryDependency.get();
install(target, factory, SERVICE_A_NAME, SERVICE_A_PREFERRED_NODE);
install(target, factory, SERVICE_B_NAME, SERVICE_B_PREFERRED_NODE);
};
builder.setInstance(new ChildTargetService(installer)).install();
new ServiceValueCaptorServiceConfigurator<>(NodeServiceExecutorRegistry.INSTANCE.add(SERVICE_A_NAME)).build(context.getServiceTarget()).install();
new ServiceValueCaptorServiceConfigurator<>(NodeServiceExecutorRegistry.INSTANCE.add(SERVICE_B_NAME)).build(context.getServiceTarget()).install();
}
private static void install(ServiceTarget target, SingletonServiceConfiguratorFactory factory, ServiceName name, String preferredNode) {
ServiceBuilder<?> builder = target.addService(name);
SingletonElectionListenerService listenerService = new SingletonElectionListenerService(builder.provides(name));
builder.setInstance(listenerService).install();
factory.createSingletonServiceConfigurator(name.append("singleton"))
.electionPolicy(new PreferredSingletonElectionPolicy(new SimpleSingletonElectionPolicy(), new NamePreference(preferredNode)))
.electionListener(listenerService)
.build(target)
.install();
}
}
| 4,641
| 54.261905
| 207
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/singleton/servlet/TraceServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.singleton.servlet;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author Paul Ferraro
*/
@WebServlet(urlPatterns = TraceServlet.SERVLET_PATH)
public class TraceServlet extends HttpServlet {
private static final long serialVersionUID = -29313922976942039L;
private static final String SERVLET_NAME = "trace";
static final String SERVLET_PATH = "/" + SERVLET_NAME;
public static URI createURI(URL baseURL) throws URISyntaxException {
return baseURL.toURI().resolve(SERVLET_NAME);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.log(request.getRequestURI());
}
}
| 2,063
| 36.527273
| 121
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/OidcBaseTest.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.ALLOWED_ORIGIN;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.http.util.TestHttpClientUtils;
import org.jboss.as.test.integration.security.common.servlets.SimpleSecuredServlet;
import org.jboss.as.test.integration.security.common.servlets.SimpleServlet;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.junit.BeforeClass;
import org.junit.Test;
import org.keycloak.representations.idm.RealmRepresentation;
import org.testcontainers.DockerClientFactory;
import org.wildfly.common.iteration.CodePointIterator;
import org.wildfly.security.jose.util.JsonSerialization;
import io.restassured.RestAssured;
/**
* Tests for the OpenID Connect authentication mechanism.
*
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
public abstract class OidcBaseTest {
public static final String CLIENT_SECRET = "secret";
public static final String OIDC_WITHOUT_SUBSYSTEM_CONFIG_WEB_XML = "web.xml";
public static KeycloakContainer KEYCLOAK_CONTAINER;
public static final String TEST_REALM = "WildFly";
private static final String KEYCLOAK_USERNAME = "username";
private static final String KEYCLOAK_PASSWORD = "password";
public static final int CLIENT_PORT = TestSuiteEnvironment.getHttpPort();
public static final String CLIENT_HOST_NAME = TestSuiteEnvironment.getHttpAddress();
public static final String PROVIDER_URL_APP = "ProviderUrlOidcApp";
public static final String AUTH_SERVER_URL_APP = "AuthServerUrlOidcApp";
public static final String WRONG_PROVIDER_URL_APP = "WrongProviderUrlOidcApp";
public static final String WRONG_SECRET_APP = "WrongSecretOidcApp";
public static final String DIRECT_ACCCESS_GRANT_ENABLED_CLIENT = "DirectAccessGrantEnabledClient";
public static final String BEARER_ONLY_AUTH_SERVER_URL_APP = "AuthServerUrlBearerOnlyApp";
public static final String BEARER_ONLY_PROVIDER_URL_APP = "ProviderUrlBearerOnlyApp";
public static final String BASIC_AUTH_PROVIDER_URL_APP = "BasicAuthProviderUrlApp";
public static final String CORS_PROVIDER_URL_APP = "CorsApp";
private static final String WRONG_PASSWORD = "WRONG_PASSWORD";
private static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
private static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
private static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
private static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
static final String ORIGIN = "Origin";
static final String ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method";
static final String ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers";
public static final String CORS_CLIENT = "CorsClient";
private enum BearerAuthType {
BEARER,
QUERY_PARAM,
BASIC
}
private static boolean isDockerAvailable() {
try {
DockerClientFactory.instance().client();
return true;
} catch (Throwable ex) {
return false;
}
}
public static void sendRealmCreationRequest(RealmRepresentation realm) {
try {
String adminAccessToken = KeycloakConfiguration.getAdminAccessToken(KEYCLOAK_CONTAINER.getAuthServerUrl());
assertNotNull(adminAccessToken);
RestAssured
.given()
.auth().oauth2(adminAccessToken)
.contentType("application/json")
.body(JsonSerialization.writeValueAsBytes(realm))
.when()
.post(KEYCLOAK_CONTAINER.getAuthServerUrl() + "/admin/realms").then()
.statusCode(201);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@BeforeClass
public static void checkDockerAvailability() {
assumeTrue("Docker isn't available, OIDC tests will be skipped", isDockerAvailable());
}
@Test
@OperateOnDeployment(PROVIDER_URL_APP)
public void testWrongPasswordWithProviderUrl() throws Exception {
loginToApp(PROVIDER_URL_APP, org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.ALICE, "WRONG_PASSWORD", HttpURLConnection.HTTP_OK, "Invalid username or password");
}
@Test
@OperateOnDeployment(PROVIDER_URL_APP)
public void testSucessfulAuthenticationWithProviderUrl() throws Exception {
loginToApp(PROVIDER_URL_APP, org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.ALICE, org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.ALICE_PASSWORD, HttpURLConnection.HTTP_OK, SimpleServlet.RESPONSE_BODY);
}
@Test
@OperateOnDeployment(PROVIDER_URL_APP)
public void testWrongRoleWithProviderUrl() throws Exception {
loginToApp(PROVIDER_URL_APP, org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.BOB, org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.BOB_PASSWORD, HttpURLConnection.HTTP_FORBIDDEN, null);
}
@Test
@OperateOnDeployment(AUTH_SERVER_URL_APP)
public void testWrongPasswordWithAuthServerUrl() throws Exception {
loginToApp(AUTH_SERVER_URL_APP, org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.ALICE, "WRONG_PASSWORD", HttpURLConnection.HTTP_OK, "Invalid username or password");
}
@Test
@OperateOnDeployment(AUTH_SERVER_URL_APP)
public void testSucessfulAuthenticationWithAuthServerUrl() throws Exception {
loginToApp(AUTH_SERVER_URL_APP, org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.ALICE, org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.ALICE_PASSWORD, HttpURLConnection.HTTP_OK, SimpleServlet.RESPONSE_BODY);
}
@Test
@OperateOnDeployment(AUTH_SERVER_URL_APP)
public void testWrongRoleWithAuthServerUrl() throws Exception {
loginToApp(AUTH_SERVER_URL_APP, org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.BOB, org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.BOB_PASSWORD, HttpURLConnection.HTTP_FORBIDDEN, null);
}
@Test
@OperateOnDeployment(WRONG_PROVIDER_URL_APP)
public void testWrongProviderUrl() throws Exception {
loginToApp(WRONG_PROVIDER_URL_APP, org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.ALICE, org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.ALICE_PASSWORD, -1, null, false);
}
@Test
@OperateOnDeployment(WRONG_SECRET_APP)
public void testWrongClientSecret() throws Exception {
loginToApp(WRONG_SECRET_APP, org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.ALICE, org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.ALICE_PASSWORD, HttpURLConnection.HTTP_FORBIDDEN, null);
}
/**
* Tests that use a bearer token.
*/
@Test
@OperateOnDeployment(BEARER_ONLY_AUTH_SERVER_URL_APP)
public void testSucessfulBearerOnlyAuthenticationWithAuthServerUrl() throws Exception {
performBearerAuthentication(BEARER_ONLY_AUTH_SERVER_URL_APP, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD,
SimpleServlet.RESPONSE_BODY, null, BearerAuthType.BEARER, DIRECT_ACCCESS_GRANT_ENABLED_CLIENT, CLIENT_SECRET);
}
@Test
@OperateOnDeployment(BEARER_ONLY_PROVIDER_URL_APP)
public void testSucessfulBearerOnlyAuthenticationWithProviderUrl() throws Exception {
performBearerAuthentication(BEARER_ONLY_PROVIDER_URL_APP, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD,
SimpleServlet.RESPONSE_BODY, null, BearerAuthType.BEARER, DIRECT_ACCCESS_GRANT_ENABLED_CLIENT, CLIENT_SECRET);
}
@Test
@OperateOnDeployment(BEARER_ONLY_PROVIDER_URL_APP)
public void testWrongToken() throws Exception {
String wrongToken = "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJrNmhQYTdHdmdrajdFdlhLeFAtRjFLZkNSUk85Q3kwNC04YzFqTERWOXNrIn0.eyJleHAiOjE2NTc2NjExODksImlhdCI6MTY1NzY2MTEyOSwianRpIjoiZThiZGQ3MWItYTA2OC00Mjc3LTkyY2UtZWJkYmU2MDVkMzBhIiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3JlYWxtcy9tYXN0ZXIiLCJhdWQiOlsibXlyZWFsbS1yZWFsbSIsIm1hc3Rlci1yZWFsbSIsImFjY291bnQiXSwic3ViIjoiZTliOGE2OWItM2RlNy00ZDYzLWFjYmItMmYyNTRhMDM1MjVkIiwidHlwIjoiQmVhcmVyIiwiYXpwIjoidGVzdC13ZWJhcHAiLCJzZXNzaW9uX3N0YXRlIjoiMTQ1OTdhMmUtOGM1Ni00YzkwLWI3NjAtZWFjYzczNWU1Zjc1IiwiYWNyIjoiMSIsInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJjcmVhdGUtcmVhbG0iLCJkZWZhdWx0LXJvbGVzLW1hc3RlciIsIm9mZmxpbmVfYWNjZXNzIiwiYWRtaW4iLCJ1bWFfYXV0aG9yaXphdGlvbiIsInVzZXIiXX0sInJlc291cmNlX2FjY2VzcyI6eyJteXJlYWxtLXJlYWxtIjp7InJvbGVzIjpbInZpZXctcmVhbG0iLCJ2aWV3LWlkZW50aXR5LXByb3ZpZGVycyIsIm1hbmFnZS1pZGVudGl0eS1wcm92aWRlcnMiLCJpbXBlcnNvbmF0aW9uIiwiY3JlYXRlLWNsaWVudCIsIm1hbmFnZS11c2VycyIsInF1ZXJ5LXJlYWxtcyIsInZpZXctYXV0aG9yaXphdGlvbiIsInF1ZXJ5LWNsaWVudHMiLCJxdWVyeS11c2VycyIsIm1hbmFnZS1ldmVudHMiLCJtYW5hZ2UtcmVhbG0iLCJ2aWV3LWV2ZW50cyIsInZpZXctdXNlcnMiLCJ2aWV3LWNsaWVudHMiLCJtYW5hZ2UtYXV0aG9yaXphdGlvbiIsIm1hbmFnZS1jbGllbnRzIiwicXVlcnktZ3JvdXBzIl19LCJtYXN0ZXItcmVhbG0iOnsicm9sZXMiOlsidmlldy1yZWFsbSIsInZpZXctaWRlbnRpdHktcHJvdmlkZXJzIiwibWFuYWdlLWlkZW50aXR5LXByb3ZpZGVycyIsImltcGVyc29uYXRpb24iLCJjcmVhdGUtY2xpZW50IiwibWFuYWdlLXVzZXJzIiwicXVlcnktcmVhbG1zIiwidmlldy1hdXRob3JpemF0aW9uIiwicXVlcnktY2xpZW50cyIsInF1ZXJ5LXVzZXJzIiwibWFuYWdlLWV2ZW50cyIsIm1hbmFnZS1yZWFsbSIsInZpZXctZXZlbnRzIiwidmlldy11c2VycyIsInZpZXctY2xpZW50cyIsIm1hbmFnZS1hdXRob3JpemF0aW9uIiwibWFuYWdlLWNsaWVudHMiLCJxdWVyeS1ncm91cHMiXX0sImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJtYW5hZ2UtYWNjb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfX0sInNjb3BlIjoiZW1haWwgcHJvZmlsZSIsInNpZCI6IjE0NTk3YTJlLThjNTYtNGM5MC1iNzYwLWVhY2M3MzVlNWY3NSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwicHJlZmVycmVkX3VzZXJuYW1lIjoiYWxpY2UifQ.hVj6SG-aTcDYhifdljpiBcz4ShCHej3h_4-82rgX0s_oJ-En68Cqt-_DgJLtMdr6dW_gQFFCPYBJfEGvZ8L6b_TwzbdLxyrQrKTOpeG0KJ8VAFlbWum9B1vvES_sav1Gj1sQHlV621EaLISYz7pnknuQEvrB7liJFRRjN9SH30AsAJy6nmKTDHGZ6Eegkveqd_7POaKfsHS3Z0-SGyL5GClXv9yZ1l5Y4VH-rrMUztLPCFH5bJ319-m-7sgizvV-C2EcM37XVAtPRVQbJNRW0wVmLEJKMuLYVnjS1Wn5eU_qnBvVMEaENNG3TzNd6b4YmxMFHFf9tnkb3wkDzdrRTA";
performBearerAuthentication(BEARER_ONLY_PROVIDER_URL_APP, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD,
SimpleServlet.RESPONSE_BODY, wrongToken, BearerAuthType.BEARER);
}
@Test
@OperateOnDeployment(BEARER_ONLY_PROVIDER_URL_APP)
public void testInvalidToken() throws Exception {
performBearerAuthentication(BEARER_ONLY_PROVIDER_URL_APP, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD,
SimpleServlet.RESPONSE_BODY, "INVALID_TOKEN", BearerAuthType.BEARER);
}
@Test
@OperateOnDeployment(BEARER_ONLY_AUTH_SERVER_URL_APP)
public void testNoTokenProvidedWithAuthServerUrl() throws Exception {
accessAppWithoutToken(BEARER_ONLY_AUTH_SERVER_URL_APP, false, true, TEST_REALM);
}
@Test
@OperateOnDeployment(BEARER_ONLY_PROVIDER_URL_APP)
public void testNoTokenProvidedWithProviderUrl() throws Exception {
accessAppWithoutToken(BEARER_ONLY_PROVIDER_URL_APP, false, true);
}
@Test
@OperateOnDeployment(PROVIDER_URL_APP)
public void testTokenProvidedBearerOnlyNotSet() throws Exception {
performBearerAuthentication(PROVIDER_URL_APP, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD,
SimpleServlet.RESPONSE_BODY, null, BearerAuthType.BEARER, DIRECT_ACCCESS_GRANT_ENABLED_CLIENT, CLIENT_SECRET);
}
@Test
@OperateOnDeployment(PROVIDER_URL_APP)
public void testTokenNotProvidedBearerOnlyNotSet() throws Exception {
// ensure the regular OIDC flow takes place
accessAppWithoutToken(PROVIDER_URL_APP, false, false,null, HttpURLConnection.HTTP_OK, SimpleServlet.RESPONSE_BODY);
}
/**
* Tests that pass the bearer token to use via an access_token query param.
*/
@Test
@OperateOnDeployment(BEARER_ONLY_PROVIDER_URL_APP)
public void testValidTokenViaQueryParameter() throws Exception {
performBearerAuthentication(BEARER_ONLY_PROVIDER_URL_APP, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD,
SimpleServlet.RESPONSE_BODY, null, BearerAuthType.QUERY_PARAM, DIRECT_ACCCESS_GRANT_ENABLED_CLIENT, CLIENT_SECRET);
}
@Test
@OperateOnDeployment(BEARER_ONLY_PROVIDER_URL_APP)
public void testWrongTokenViaQueryParameter() throws Exception {
String wrongToken = "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJrNmhQYTdHdmdrajdFdlhLeFAtRjFLZkNSUk85Q3kwNC04YzFqTERWOXNrIn0.eyJleHAiOjE2NTc2NjExODksImlhdCI6MTY1NzY2MTEyOSwianRpIjoiZThiZGQ3MWItYTA2OC00Mjc3LTkyY2UtZWJkYmU2MDVkMzBhIiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3JlYWxtcy9tYXN0ZXIiLCJhdWQiOlsibXlyZWFsbS1yZWFsbSIsIm1hc3Rlci1yZWFsbSIsImFjY291bnQiXSwic3ViIjoiZTliOGE2OWItM2RlNy00ZDYzLWFjYmItMmYyNTRhMDM1MjVkIiwidHlwIjoiQmVhcmVyIiwiYXpwIjoidGVzdC13ZWJhcHAiLCJzZXNzaW9uX3N0YXRlIjoiMTQ1OTdhMmUtOGM1Ni00YzkwLWI3NjAtZWFjYzczNWU1Zjc1IiwiYWNyIjoiMSIsInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJjcmVhdGUtcmVhbG0iLCJkZWZhdWx0LXJvbGVzLW1hc3RlciIsIm9mZmxpbmVfYWNjZXNzIiwiYWRtaW4iLCJ1bWFfYXV0aG9yaXphdGlvbiIsInVzZXIiXX0sInJlc291cmNlX2FjY2VzcyI6eyJteXJlYWxtLXJlYWxtIjp7InJvbGVzIjpbInZpZXctcmVhbG0iLCJ2aWV3LWlkZW50aXR5LXByb3ZpZGVycyIsIm1hbmFnZS1pZGVudGl0eS1wcm92aWRlcnMiLCJpbXBlcnNvbmF0aW9uIiwiY3JlYXRlLWNsaWVudCIsIm1hbmFnZS11c2VycyIsInF1ZXJ5LXJlYWxtcyIsInZpZXctYXV0aG9yaXphdGlvbiIsInF1ZXJ5LWNsaWVudHMiLCJxdWVyeS11c2VycyIsIm1hbmFnZS1ldmVudHMiLCJtYW5hZ2UtcmVhbG0iLCJ2aWV3LWV2ZW50cyIsInZpZXctdXNlcnMiLCJ2aWV3LWNsaWVudHMiLCJtYW5hZ2UtYXV0aG9yaXphdGlvbiIsIm1hbmFnZS1jbGllbnRzIiwicXVlcnktZ3JvdXBzIl19LCJtYXN0ZXItcmVhbG0iOnsicm9sZXMiOlsidmlldy1yZWFsbSIsInZpZXctaWRlbnRpdHktcHJvdmlkZXJzIiwibWFuYWdlLWlkZW50aXR5LXByb3ZpZGVycyIsImltcGVyc29uYXRpb24iLCJjcmVhdGUtY2xpZW50IiwibWFuYWdlLXVzZXJzIiwicXVlcnktcmVhbG1zIiwidmlldy1hdXRob3JpemF0aW9uIiwicXVlcnktY2xpZW50cyIsInF1ZXJ5LXVzZXJzIiwibWFuYWdlLWV2ZW50cyIsIm1hbmFnZS1yZWFsbSIsInZpZXctZXZlbnRzIiwidmlldy11c2VycyIsInZpZXctY2xpZW50cyIsIm1hbmFnZS1hdXRob3JpemF0aW9uIiwibWFuYWdlLWNsaWVudHMiLCJxdWVyeS1ncm91cHMiXX0sImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJtYW5hZ2UtYWNjb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfX0sInNjb3BlIjoiZW1haWwgcHJvZmlsZSIsInNpZCI6IjE0NTk3YTJlLThjNTYtNGM5MC1iNzYwLWVhY2M3MzVlNWY3NSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwicHJlZmVycmVkX3VzZXJuYW1lIjoiYWxpY2UifQ.hVj6SG-aTcDYhifdljpiBcz4ShCHej3h_4-82rgX0s_oJ-En68Cqt-_DgJLtMdr6dW_gQFFCPYBJfEGvZ8L6b_TwzbdLxyrQrKTOpeG0KJ8VAFlbWum9B1vvES_sav1Gj1sQHlV621EaLISYz7pnknuQEvrB7liJFRRjN9SH30AsAJy6nmKTDHGZ6Eegkveqd_7POaKfsHS3Z0-SGyL5GClXv9yZ1l5Y4VH-rrMUztLPCFH5bJ319-m-7sgizvV-C2EcM37XVAtPRVQbJNRW0wVmLEJKMuLYVnjS1Wn5eU_qnBvVMEaENNG3TzNd6b4YmxMFHFf9tnkb3wkDzdrRTA";
performBearerAuthentication(BEARER_ONLY_PROVIDER_URL_APP, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD,
SimpleServlet.RESPONSE_BODY, wrongToken, BearerAuthType.QUERY_PARAM);
}
@Test
@OperateOnDeployment(BEARER_ONLY_PROVIDER_URL_APP)
public void testInvalidTokenViaQueryParameter() throws Exception {
performBearerAuthentication(BEARER_ONLY_PROVIDER_URL_APP, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD,
SimpleServlet.RESPONSE_BODY, "INVALID_TOKEN", BearerAuthType.QUERY_PARAM);
}
/**
* Tests that rely on obtaining the bearer token to use from credentials obtained from basic auth.
*/
@Test
@OperateOnDeployment(BEARER_ONLY_PROVIDER_URL_APP)
public void testBasicAuthenticationWithoutEnableBasicAuthSet() throws Exception {
accessAppWithoutToken(BEARER_ONLY_PROVIDER_URL_APP, true, true, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD);
}
@Test
@OperateOnDeployment(PROVIDER_URL_APP)
public void testBasicAuthenticationWithoutEnableBasicAuthSetAndWithoutBearerOnlySet() throws Exception {
// ensure the regular OIDC flow takes place
accessAppWithoutToken(PROVIDER_URL_APP, true, false, null, HttpURLConnection.HTTP_OK, SimpleServlet.RESPONSE_BODY);
}
@Test
@OperateOnDeployment(BASIC_AUTH_PROVIDER_URL_APP)
public void testValidCredentialsBasicAuthentication() throws Exception {
performBearerAuthentication(BASIC_AUTH_PROVIDER_URL_APP, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD,
SimpleServlet.RESPONSE_BODY, null, BearerAuthType.BASIC);
}
@Test
@OperateOnDeployment(BASIC_AUTH_PROVIDER_URL_APP)
public void testInvalidCredentialsBasicAuthentication() throws Exception {
accessAppWithoutToken(BASIC_AUTH_PROVIDER_URL_APP, true, true, KeycloakConfiguration.ALICE, WRONG_PASSWORD);
}
/**
* Tests that simulate CORS preflight requests.
*/
@Test
@OperateOnDeployment(CORS_PROVIDER_URL_APP)
public void testCorsRequestWithEnableCors() throws Exception {
performBearerAuthenticationWithCors(CORS_PROVIDER_URL_APP, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD,
SimpleServlet.RESPONSE_BODY, null, CORS_CLIENT, CLIENT_SECRET, ALLOWED_ORIGIN, true);
}
@Test
@OperateOnDeployment(CORS_PROVIDER_URL_APP)
public void testCorsRequestWithEnableCorsWithWrongToken() throws Exception {
String wrongToken = "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJrNmhQYTdHdmdrajdFdlhLeFAtRjFLZkNSUk85Q3kwNC04YzFqTERWOXNrIn0.eyJleHAiOjE2NTc2NjExODksImlhdCI6MTY1NzY2MTEyOSwianRpIjoiZThiZGQ3MWItYTA2OC00Mjc3LTkyY2UtZWJkYmU2MDVkMzBhIiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3JlYWxtcy9tYXN0ZXIiLCJhdWQiOlsibXlyZWFsbS1yZWFsbSIsIm1hc3Rlci1yZWFsbSIsImFjY291bnQiXSwic3ViIjoiZTliOGE2OWItM2RlNy00ZDYzLWFjYmItMmYyNTRhMDM1MjVkIiwidHlwIjoiQmVhcmVyIiwiYXpwIjoidGVzdC13ZWJhcHAiLCJzZXNzaW9uX3N0YXRlIjoiMTQ1OTdhMmUtOGM1Ni00YzkwLWI3NjAtZWFjYzczNWU1Zjc1IiwiYWNyIjoiMSIsInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJjcmVhdGUtcmVhbG0iLCJkZWZhdWx0LXJvbGVzLW1hc3RlciIsIm9mZmxpbmVfYWNjZXNzIiwiYWRtaW4iLCJ1bWFfYXV0aG9yaXphdGlvbiIsInVzZXIiXX0sInJlc291cmNlX2FjY2VzcyI6eyJteXJlYWxtLXJlYWxtIjp7InJvbGVzIjpbInZpZXctcmVhbG0iLCJ2aWV3LWlkZW50aXR5LXByb3ZpZGVycyIsIm1hbmFnZS1pZGVudGl0eS1wcm92aWRlcnMiLCJpbXBlcnNvbmF0aW9uIiwiY3JlYXRlLWNsaWVudCIsIm1hbmFnZS11c2VycyIsInF1ZXJ5LXJlYWxtcyIsInZpZXctYXV0aG9yaXphdGlvbiIsInF1ZXJ5LWNsaWVudHMiLCJxdWVyeS11c2VycyIsIm1hbmFnZS1ldmVudHMiLCJtYW5hZ2UtcmVhbG0iLCJ2aWV3LWV2ZW50cyIsInZpZXctdXNlcnMiLCJ2aWV3LWNsaWVudHMiLCJtYW5hZ2UtYXV0aG9yaXphdGlvbiIsIm1hbmFnZS1jbGllbnRzIiwicXVlcnktZ3JvdXBzIl19LCJtYXN0ZXItcmVhbG0iOnsicm9sZXMiOlsidmlldy1yZWFsbSIsInZpZXctaWRlbnRpdHktcHJvdmlkZXJzIiwibWFuYWdlLWlkZW50aXR5LXByb3ZpZGVycyIsImltcGVyc29uYXRpb24iLCJjcmVhdGUtY2xpZW50IiwibWFuYWdlLXVzZXJzIiwicXVlcnktcmVhbG1zIiwidmlldy1hdXRob3JpemF0aW9uIiwicXVlcnktY2xpZW50cyIsInF1ZXJ5LXVzZXJzIiwibWFuYWdlLWV2ZW50cyIsIm1hbmFnZS1yZWFsbSIsInZpZXctZXZlbnRzIiwidmlldy11c2VycyIsInZpZXctY2xpZW50cyIsIm1hbmFnZS1hdXRob3JpemF0aW9uIiwibWFuYWdlLWNsaWVudHMiLCJxdWVyeS1ncm91cHMiXX0sImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJtYW5hZ2UtYWNjb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfX0sInNjb3BlIjoiZW1haWwgcHJvZmlsZSIsInNpZCI6IjE0NTk3YTJlLThjNTYtNGM5MC1iNzYwLWVhY2M3MzVlNWY3NSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwicHJlZmVycmVkX3VzZXJuYW1lIjoiYWxpY2UifQ.hVj6SG-aTcDYhifdljpiBcz4ShCHej3h_4-82rgX0s_oJ-En68Cqt-_DgJLtMdr6dW_gQFFCPYBJfEGvZ8L6b_TwzbdLxyrQrKTOpeG0KJ8VAFlbWum9B1vvES_sav1Gj1sQHlV621EaLISYz7pnknuQEvrB7liJFRRjN9SH30AsAJy6nmKTDHGZ6Eegkveqd_7POaKfsHS3Z0-SGyL5GClXv9yZ1l5Y4VH-rrMUztLPCFH5bJ319-m-7sgizvV-C2EcM37XVAtPRVQbJNRW0wVmLEJKMuLYVnjS1Wn5eU_qnBvVMEaENNG3TzNd6b4YmxMFHFf9tnkb3wkDzdrRTA";
performBearerAuthenticationWithCors(CORS_PROVIDER_URL_APP, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD,
SimpleServlet.RESPONSE_BODY, wrongToken, CORS_CLIENT, CLIENT_SECRET, ALLOWED_ORIGIN, true);
}
@Test
@OperateOnDeployment(CORS_PROVIDER_URL_APP)
public void testCorsRequestWithEnableCorsWithInvalidToken() throws Exception {
performBearerAuthenticationWithCors(CORS_PROVIDER_URL_APP, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD,
SimpleServlet.RESPONSE_BODY, "INVALID_TOKEN", CORS_CLIENT, CLIENT_SECRET, ALLOWED_ORIGIN, true);
}
@Test
@OperateOnDeployment(CORS_PROVIDER_URL_APP)
public void testCorsRequestWithEnableCorsWithInvalidOrigin() throws Exception {
performBearerAuthenticationWithCors(CORS_PROVIDER_URL_APP, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD,
SimpleServlet.RESPONSE_BODY, null, CORS_CLIENT, CLIENT_SECRET, "http://invalidorigin", true);
}
@Test
@OperateOnDeployment(BEARER_ONLY_PROVIDER_URL_APP)
public void testCorsRequestWithoutEnableCors() throws Exception {
performBearerAuthenticationWithCors(BEARER_ONLY_PROVIDER_URL_APP, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD,
SimpleServlet.RESPONSE_BODY, null, CORS_CLIENT, CLIENT_SECRET, ALLOWED_ORIGIN, false);
}
public static void loginToApp(String appName, String username, String password, int expectedStatusCode, String expectedText) throws Exception {
loginToApp(username, password, expectedStatusCode, expectedText, true,
new URL("http", TestSuiteEnvironment.getHttpAddress(), TestSuiteEnvironment.getHttpPort(),
"/" + appName + SimpleSecuredServlet.SERVLET_PATH).toURI());
}
public static void loginToApp(String appName, String username, String password, int expectedStatusCode, String expectedText, URI requestUri) throws Exception {
loginToApp(username, password, expectedStatusCode, expectedText, true, requestUri);
}
public static void loginToApp(String appName, String username, String password, int expectedStatusCode, String expectedText, boolean loginToKeycloak) throws Exception {
loginToApp(username, password, expectedStatusCode, expectedText, loginToKeycloak, new URL("http", TestSuiteEnvironment.getHttpAddress(), TestSuiteEnvironment.getHttpPort(),
"/" + appName + SimpleSecuredServlet.SERVLET_PATH).toURI());
}
public static void loginToApp(String username, String password, int expectedStatusCode, String expectedText, boolean loginToKeycloak, URI requestUri) throws Exception {
CookieStore store = new BasicCookieStore();
HttpClient httpClient = TestHttpClientUtils.promiscuousCookieHttpClientBuilder()
.setDefaultCookieStore(store)
.setRedirectStrategy(new LaxRedirectStrategy())
.build();
HttpGet getMethod = new HttpGet(requestUri);
HttpContext context = new BasicHttpContext();
HttpResponse response = httpClient.execute(getMethod, context);
try {
int statusCode = response.getStatusLine().getStatusCode();
if (loginToKeycloak) {
assertTrue("Expected code == OK but got " + statusCode + " for request=" + requestUri, statusCode == HttpURLConnection.HTTP_OK);
Form keycloakLoginForm = new Form(response);
HttpResponse afterLoginClickResponse = simulateClickingOnButton(httpClient, keycloakLoginForm, username, password, "Sign In");
afterLoginClickResponse.getEntity().getContent();
assertEquals(expectedStatusCode, afterLoginClickResponse.getStatusLine().getStatusCode());
if (expectedText != null) {
String responseString = new BasicResponseHandler().handleResponse(afterLoginClickResponse);
assertTrue("Unexpected result " + responseString, responseString.contains(expectedText));
}
} else {
assertTrue("Expected code == FORBIDDEN but got " + statusCode + " for request=" + requestUri, statusCode == HttpURLConnection.HTTP_FORBIDDEN);
}
} finally {
HttpClientUtils.closeQuietly(response);
}
}
private void performBearerAuthentication(String appName, String username, String password,
String clientPageText, String bearerToken, BearerAuthType bearerAuthType) throws Exception {
performBearerAuthentication(appName, username, password, clientPageText, bearerToken, bearerAuthType, null, null);
}
private void performBearerAuthentication(String appName, String username, String password,
String clientPageText, String bearerToken, BearerAuthType bearerAuthType,
String clientId, String clientSecret) throws Exception {
HttpClient httpClient = HttpClients.createDefault();
HttpGet getMethod;
HttpContext context = new BasicHttpContext();
HttpResponse response;
URI requestUri;
switch (bearerAuthType) {
case QUERY_PARAM:
if (bearerToken == null) {
// obtain a bearer token and then try accessing the endpoint with a query param specified
requestUri = new URL("http", TestSuiteEnvironment.getHttpAddress(), TestSuiteEnvironment.getHttpPort(),
"/" + appName + SimpleSecuredServlet.SERVLET_PATH + "?access_token="
+ KeycloakConfiguration.getAccessToken(KEYCLOAK_CONTAINER.getAuthServerUrl(), TEST_REALM, username,
password, clientId, clientSecret)).toURI();
} else {
// try accessing the endpoint with the given bearer token specified using a query param
requestUri = new URL("http", TestSuiteEnvironment.getHttpAddress(), TestSuiteEnvironment.getHttpPort(),
"/" + appName + SimpleSecuredServlet.SERVLET_PATH + "?access_token=" + bearerToken).toURI();
}
getMethod = new HttpGet(requestUri);
break;
case BASIC:
requestUri = new URL("http", TestSuiteEnvironment.getHttpAddress(), TestSuiteEnvironment.getHttpPort(),
"/" + appName + SimpleSecuredServlet.SERVLET_PATH).toURI();
getMethod = new HttpGet(requestUri);
getMethod.addHeader("Authorization", "Basic " + CodePointIterator.ofString(username + ":" + password).asUtf8().base64Encode().drainToString());
break;
default: // BEARER
requestUri = new URL("http", TestSuiteEnvironment.getHttpAddress(), TestSuiteEnvironment.getHttpPort(),
"/" + appName + SimpleSecuredServlet.SERVLET_PATH).toURI();
getMethod = new HttpGet(requestUri);
if (bearerToken == null) {
// obtain a bearer token and then try accessing the endpoint with the Authorization header specified
getMethod.addHeader("Authorization", "Bearer " + KeycloakConfiguration.getAccessToken(KEYCLOAK_CONTAINER.getAuthServerUrl(), TEST_REALM, username,
password, clientId, clientSecret));
} else {
// try accessing the endpoint with the given bearer token specified using the Authorization header
getMethod.addHeader("Authorization", "Bearer " + bearerToken);
}
break;
}
response = httpClient.execute(getMethod, context);
try {
int statusCode = response.getStatusLine().getStatusCode();
if (bearerToken == null) {
assertEquals(HttpURLConnection.HTTP_OK, statusCode);
String responseString = new BasicResponseHandler().handleResponse(response);
assertTrue(responseString.contains(clientPageText));
} else {
assertTrue("Expected code == UNAUTHORIZED but got " + statusCode + " for request=" + requestUri, statusCode == HttpURLConnection.HTTP_UNAUTHORIZED);
}
} finally {
HttpClientUtils.closeQuietly(response);
}
}
private void performBearerAuthenticationWithCors(String appName, String username, String password,
String clientPageText, String bearerToken,
String clientId, String clientSecret, String originHeader, boolean corsEnabled) throws Exception {
URI requestUri = new URL("http", TestSuiteEnvironment.getHttpAddress(), TestSuiteEnvironment.getHttpPort(),
"/" + appName + SimpleSecuredServlet.SERVLET_PATH).toURI();
HttpClient httpClient = HttpClients.createDefault();
HttpOptions optionsMethod = new HttpOptions(requestUri);
HttpContext context = new BasicHttpContext();
HttpResponse response;
optionsMethod.addHeader(ORIGIN, originHeader);
optionsMethod.addHeader(ACCESS_CONTROL_REQUEST_HEADERS, "authorization");
optionsMethod.addHeader(ACCESS_CONTROL_REQUEST_METHOD, "GET");
response = httpClient.execute(optionsMethod, context);
try {
int statusCode = response.getStatusLine().getStatusCode();
if (corsEnabled) {
assertEquals(HttpURLConnection.HTTP_OK, statusCode);
assertTrue(Boolean.valueOf(response.getFirstHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS).getValue()));
assertEquals("authorization", response.getFirstHeader(ACCESS_CONTROL_ALLOW_HEADERS).getValue());
assertEquals("GET", response.getFirstHeader(ACCESS_CONTROL_ALLOW_METHODS).getValue());
assertEquals(originHeader, response.getFirstHeader(ACCESS_CONTROL_ALLOW_ORIGIN).getValue());
HttpGet getMethod = new HttpGet(requestUri);
getMethod.addHeader(ORIGIN, originHeader);
if (bearerToken == null) {
// obtain a bearer token and then try accessing the endpoint with the Authorization header specified
getMethod.addHeader("Authorization", "Bearer " + KeycloakConfiguration.getAccessToken(KEYCLOAK_CONTAINER.getAuthServerUrl(), TEST_REALM, username,
password, clientId, clientSecret));
} else {
// try accessing the endpoint with the given bearer token specified using the Authorization header
getMethod.addHeader("Authorization", "Bearer " + bearerToken);
}
response = httpClient.execute(getMethod, context);
statusCode = response.getStatusLine().getStatusCode();
if (bearerToken == null) {
if (originHeader.equals(ALLOWED_ORIGIN)) {
assertEquals(HttpURLConnection.HTTP_OK, statusCode);
String responseString = new BasicResponseHandler().handleResponse(response);
assertTrue(responseString.contains(clientPageText));
} else {
assertEquals(HttpURLConnection.HTTP_FORBIDDEN, statusCode);
}
} else {
assertTrue("Expected code == UNAUTHORIZED but got " + statusCode + " for request=" + requestUri, statusCode == HttpURLConnection.HTTP_UNAUTHORIZED);
}
} else {
assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, statusCode);
Header authenticateHeader = response.getFirstHeader("WWW-Authenticate");
assertEquals("Bearer", authenticateHeader.getValue());
}
} finally {
HttpClientUtils.closeQuietly(response);
}
}
private void accessAppWithoutToken(String appName, boolean includeBasicHeader, boolean bearerOnlyOrEnableBasicConfigured) throws Exception {
accessAppWithoutToken(appName, includeBasicHeader, bearerOnlyOrEnableBasicConfigured, null);
}
private void accessAppWithoutToken(String appName, boolean includeBasicHeader, boolean bearerOnlyOrEnableBasicConfigured, String realm) throws Exception {
accessAppWithoutToken(appName, includeBasicHeader, bearerOnlyOrEnableBasicConfigured, realm, -1, null);
}
private void accessAppWithoutToken(String appName, boolean includeBasicHeader, boolean bearerOnlyOrEnableBasicConfigured, String realm, int expectedStatusCode, String expectedText) throws Exception {
accessAppWithoutToken(appName, includeBasicHeader, bearerOnlyOrEnableBasicConfigured, realm, expectedStatusCode, expectedText, null, null);
}
private void accessAppWithoutToken(String appName, boolean includeBasicHeader, boolean bearerOnlyOrEnableBasicConfigured, String username, String password) throws Exception {
accessAppWithoutToken(appName, includeBasicHeader, bearerOnlyOrEnableBasicConfigured, null, -1, null, username, password);
}
private void accessAppWithoutToken(String appName, boolean includeBasicHeader, boolean bearerOnlyOrEnableBasicConfigured, String realm, int expectedStatusCode, String expectedText,
String username, String password) throws Exception {
final URI requestUri = new URL("http", TestSuiteEnvironment.getHttpAddress(), TestSuiteEnvironment.getHttpPort(),
"/" + appName + SimpleSecuredServlet.SERVLET_PATH).toURI();
CookieStore store = new BasicCookieStore();
HttpClient httpClient = TestHttpClientUtils.promiscuousCookieHttpClientBuilder()
.setDefaultCookieStore(store)
.setRedirectStrategy(new LaxRedirectStrategy())
.build();
HttpGet getMethod = new HttpGet(requestUri);
if (includeBasicHeader) {
getMethod.addHeader("Authorization", "Basic " + CodePointIterator.ofString(username + ":" + password).asUtf8().base64Encode().drainToString());
}
HttpContext context = new BasicHttpContext();
HttpResponse response = httpClient.execute(getMethod, context);
try {
int statusCode = response.getStatusLine().getStatusCode();
if (bearerOnlyOrEnableBasicConfigured) {
assertTrue("Expected code == UNAUTHORIZED but got " + statusCode + " for request=" + requestUri, statusCode == HttpURLConnection.HTTP_UNAUTHORIZED);
Header authenticateHeader = response.getFirstHeader("WWW-Authenticate");
String authenticateValue = authenticateHeader.getValue();
if (password != null && password.equals(WRONG_PASSWORD)) {
assertTrue(authenticateValue.startsWith("Bearer error=\"" + "no_token" + "\""));
assertTrue(authenticateValue.contains("error_description"));
assertTrue(authenticateValue.contains(String.valueOf(HttpURLConnection.HTTP_UNAUTHORIZED)));
} else if (realm != null) {
assertEquals("Bearer realm=\"" + TEST_REALM + "\"", authenticateValue);
} else {
assertEquals("Bearer", authenticateValue);
}
} else {
// no token provided and bearer-only is not configured, should end up in the OIDC flow
assertTrue("Expected code == OK but got " + statusCode + " for request=" + requestUri, statusCode == HttpURLConnection.HTTP_OK);
Form keycloakLoginForm = new Form(response);
HttpResponse afterLoginClickResponse = simulateClickingOnButton(httpClient, keycloakLoginForm,
KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD, "Sign In");
afterLoginClickResponse.getEntity().getContent();
assertEquals(expectedStatusCode, afterLoginClickResponse.getStatusLine().getStatusCode());
if (expectedText != null) {
String responseString = new BasicResponseHandler().handleResponse(afterLoginClickResponse);
assertTrue(responseString.contains(expectedText));
}
}
} finally {
HttpClientUtils.closeQuietly(response);
}
}
public static class KeycloakSetup implements ServerSetupTask {
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
KEYCLOAK_CONTAINER = new KeycloakContainer();
KEYCLOAK_CONTAINER.start();
}
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
if (KEYCLOAK_CONTAINER != null) {
KEYCLOAK_CONTAINER.stop();
}
}
}
private static HttpResponse simulateClickingOnButton(HttpClient client, Form form, String username, String password, String buttonValue) throws IOException {
final URL url = new URL(form.getAction());
final HttpPost request = new HttpPost(url.toString());
final List<NameValuePair> params = new LinkedList<>();
for (Input input : form.getInputFields()) {
if (input.type == Input.Type.HIDDEN ||
(input.type == Input.Type.SUBMIT && input.getValue().equals(buttonValue))) {
params.add(new BasicNameValuePair(input.getName(), input.getValue()));
} else if (input.getName().equals(KEYCLOAK_USERNAME)) {
params.add(new BasicNameValuePair(input.getName(), username));
} else if (input.getName().equals(KEYCLOAK_PASSWORD)) {
params.add(new BasicNameValuePair(input.getName(), password));
}
}
request.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
return client.execute(request);
}
public static final class Form {
static final String
NAME = "name",
VALUE = "value",
INPUT = "input",
TYPE = "type",
ACTION = "action",
FORM = "form";
final HttpResponse response;
final String action;
final List<Input> inputFields = new LinkedList<>();
public Form(HttpResponse response) throws IOException {
this.response = response;
final String responseString = new BasicResponseHandler().handleResponse(response);
final Document doc = Jsoup.parse(responseString);
final Element form = doc.select(FORM).first();
this.action = form.attr(ACTION);
for (Element input : form.select(INPUT)) {
Input.Type type = null;
switch (input.attr(TYPE)) {
case "submit":
type = Input.Type.SUBMIT;
break;
case "hidden":
type = Input.Type.HIDDEN;
break;
}
inputFields.add(new Input(input.attr(NAME), input.attr(VALUE), type));
}
}
public String getAction() {
return action;
}
public List<Input> getInputFields() {
return inputFields;
}
}
private static final class Input {
final String name, value;
final Input.Type type;
public Input(String name, String value, Input.Type type) {
this.name = name;
this.value = value;
this.type = type;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public enum Type {
HIDDEN, SUBMIT
}
}
}
| 42,345
| 61.090909
| 2,252
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/KeycloakContainer.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021 Red Hat, Inc., and individual 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.wildfly.test.integration.elytron.oidc.client;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.strategy.Wait;
/**
* KeycloakContainer for testing.
*
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
public class KeycloakContainer extends GenericContainer<KeycloakContainer> {
public static final String ADMIN_USER = "admin";
public static final String ADMIN_PASSWORD = "admin";
private static final String KEYCLOAK_IMAGE = "quay.io/keycloak/keycloak:19.0.1";
private static final String SSO_IMAGE = System.getProperty("testsuite.integration.oidc.rhsso.image",KEYCLOAK_IMAGE);
private static final int PORT_HTTP = 8080;
private static final int PORT_HTTPS = 8443;
private boolean useHttps;
public KeycloakContainer() {
this(false);
}
public KeycloakContainer(final boolean useHttps) {
super(SSO_IMAGE);
this.useHttps = useHttps;
}
@Override
protected void configure() {
withExposedPorts(PORT_HTTP, PORT_HTTPS);
withEnv("KEYCLOAK_ADMIN", ADMIN_USER);
withEnv("KEYCLOAK_ADMIN_PASSWORD", ADMIN_PASSWORD);
withEnv("SSO_ADMIN_USERNAME", ADMIN_USER);
withEnv("SSO_ADMIN_PASSWORD", ADMIN_PASSWORD);
if (isUsedRHSSOImage()) {
waitingFor(Wait.forHttp("/auth").forPort(PORT_HTTP));
}else{
waitingFor(Wait.forLogMessage(".*Keycloak.*started.*", 1));
withCommand("start-dev");
}
}
public String getAuthServerUrl() {
Integer port = useHttps ? getMappedPort(PORT_HTTPS) : getMappedPort(PORT_HTTP);
String authServerUrl = String.format("http://%s:%s", getContainerIpAddress(), port);
if(isUsedRHSSOImage()){
authServerUrl += "/auth";
}
return authServerUrl;
}
private boolean isUsedRHSSOImage(){
return SSO_IMAGE.contains("rh-sso");
}
}
| 2,675
| 34.210526
| 120
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/KeycloakConfiguration.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021 Red Hat, Inc., and individual 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.wildfly.test.integration.elytron.oidc.client;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.representations.idm.RolesRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
/**
* Keycloak configuration for testing.
*
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
public class KeycloakConfiguration {
private static final String USER_ROLE = "user";
public static final String JBOSS_ADMIN_ROLE = "JBossAdmin";
public static final String ALICE = "alice";
public static final String ALICE_PASSWORD = "alice123+";
public static final String BOB = "bob";
public static final String BOB_PASSWORD = "bob123+";
public static final String CHARLIE = "charlie";
public static final String CHARLIE_PASSWORD = "charlie123+";
public static final String ALLOWED_ORIGIN = "http://somehost";
public enum ClientAppType {
OIDC_CLIENT,
DIRECT_ACCESS_GRANT_OIDC_CLIENT,
BEARER_ONLY_CLIENT,
CORS_CLIENT
}
/**
* Configure RealmRepresentation as follows:
* <ul>
* <li>Two realm roles ("JBossAdmin", "user")</li>
* <li>Two users:<li>
* <ul>
* <li>user named alice and password alice123+ with "JBossAdmin" and "user" role</li>
* <li>user named bob and password bob123+ with "user" role</li>
* </ul>
* </ul>
*/
public static RealmRepresentation getRealmRepresentation(final String realmName, String clientSecret,
String clientHostName, int clientPort, Map<String, ClientAppType> clientApps) {
return createRealm(realmName, clientSecret, clientHostName, clientPort, clientApps);
}
public static String getAdminAccessToken(String authServerUrl) {
RequestSpecification requestSpecification = RestAssured
.given()
.param("grant_type", "password")
.param("username", KeycloakContainer.ADMIN_USER)
.param("password", KeycloakContainer.ADMIN_PASSWORD)
.param("client_id", "admin-cli");
Response response = requestSpecification.when().post(authServerUrl + "/realms/master/protocol/openid-connect/token");
final long deadline = System.currentTimeMillis() + 180000;
while (response.getStatusCode() != 200) {
// the Keycloak admin user isn't available yet, keep trying until it is to ensure we can obtain the token
// needed to set up the realms for the test
response = requestSpecification.when().post(authServerUrl + "/realms/master/protocol/openid-connect/token");
if (System.currentTimeMillis() > deadline) {
return null;
}
}
return response.as(AccessTokenResponse.class).getToken();
}
public static String getAccessToken(String authServerUrl, String realmName, String username, String password, String clientId, String clientSecret) {
return RestAssured
.given()
.param("grant_type", "password")
.param("username", username)
.param("password", password)
.param("client_id", clientId)
.param("client_secret", clientSecret)
.when()
.post(authServerUrl + "/realms/" + realmName + "/protocol/openid-connect/token")
.as(AccessTokenResponse.class).getToken();
}
private static RealmRepresentation createRealm(String name, String clientSecret,
String clientHostName, int clientPort, Map<String, ClientAppType> clientApps) {
RealmRepresentation realm = new RealmRepresentation();
realm.setRealm(name);
realm.setEnabled(true);
realm.setUsers(new ArrayList<>());
realm.setClients(new ArrayList<>());
realm.setAccessTokenLifespan(3);
realm.setSsoSessionMaxLifespan(3);
RolesRepresentation roles = new RolesRepresentation();
List<RoleRepresentation> realmRoles = new ArrayList<>();
roles.setRealm(realmRoles);
realm.setRoles(roles);
realm.getRoles().getRealm().add(new RoleRepresentation(USER_ROLE, null, false));
realm.getRoles().getRealm().add(new RoleRepresentation(JBOSS_ADMIN_ROLE, null, false));
for (Map.Entry<String, ClientAppType> entry : clientApps.entrySet()) {
String clientApp = entry.getKey();
switch (entry.getValue()) {
case DIRECT_ACCESS_GRANT_OIDC_CLIENT:
realm.getClients().add(createWebAppClient(clientApp, clientSecret, clientHostName, clientPort, clientApp, true));
break;
case BEARER_ONLY_CLIENT:
realm.getClients().add(createBearerOnlyClient(clientApp));
break;
case CORS_CLIENT:
realm.getClients().add(createWebAppClient(clientApp, clientSecret, clientHostName, clientPort, clientApp, true, ALLOWED_ORIGIN));
break;
default:
realm.getClients().add(createWebAppClient(clientApp, clientSecret, clientHostName, clientPort, clientApp, false));
}
}
realm.getUsers().add(createUser(ALICE, ALICE_PASSWORD, Arrays.asList(USER_ROLE, JBOSS_ADMIN_ROLE)));
realm.getUsers().add(createUser(BOB, BOB_PASSWORD, Arrays.asList(USER_ROLE)));
realm.getUsers().add(createUser(CHARLIE, CHARLIE_PASSWORD, Arrays.asList(USER_ROLE, JBOSS_ADMIN_ROLE)));
return realm;
}
private static ClientRepresentation createWebAppClient(String clientId, String clientSecret, String clientHostName, int clientPort,
String clientApp, boolean directAccessGrantEnabled) {
return createWebAppClient(clientId, clientSecret, clientHostName, clientPort, clientApp, directAccessGrantEnabled, null);
}
private static ClientRepresentation createWebAppClient(String clientId, String clientSecret, String clientHostName, int clientPort,
String clientApp, boolean directAccessGrantEnabled, String allowedOrigin) {
ClientRepresentation client = new ClientRepresentation();
client.setClientId(clientId);
client.setPublicClient(false);
client.setSecret(clientSecret);
//client.setRedirectUris(Arrays.asList("*"));
client.setRedirectUris(Arrays.asList("http://" + clientHostName + ":" + clientPort + "/" + clientApp + "/*"));
client.setEnabled(true);
client.setDirectAccessGrantsEnabled(directAccessGrantEnabled);
if (allowedOrigin != null) {
client.setWebOrigins(Collections.singletonList(allowedOrigin));
}
return client;
}
private static ClientRepresentation createBearerOnlyClient(String clientId) {
ClientRepresentation client = new ClientRepresentation();
client.setClientId(clientId);
client.setBearerOnly(true);
client.setEnabled(true);
return client;
}
private static UserRepresentation createUser(String username, String password, List<String> realmRoles) {
UserRepresentation user = new UserRepresentation();
user.setUsername(username);
user.setEnabled(true);
user.setCredentials(new ArrayList<>());
user.setRealmRoles(realmRoles);
user.setEmail(username + "@gmail.com");
CredentialRepresentation credential = new CredentialRepresentation();
credential.setType(CredentialRepresentation.PASSWORD);
credential.setValue(password);
credential.setTemporary(false);
user.getCredentials().add(credential);
return user;
}
}
| 9,108
| 43.871921
| 153
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/OidcIdentityPropagationTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation;
import static org.jboss.as.cli.Util.REMOVE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.operations.common.Util.createAddOperation;
import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assume.assumeTrue;
import static org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.getRealmRepresentation;
import static org.wildfly.test.integration.elytron.oidc.client.OidcBaseTest.KEYCLOAK_CONTAINER;
import static org.wildfly.test.integration.elytron.oidc.client.OidcBaseTest.loginToApp;
import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.integration.management.base.AbstractMgmtTestBase;
import org.jboss.as.test.integration.management.util.ModelUtil;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.as.test.shared.integration.ejb.security.Util;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.testcontainers.DockerClientFactory;
import org.wildfly.extension.elytron.oidc.ElytronOidcExtension;
import org.wildfly.security.permission.ElytronPermission;
import org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration;
import org.wildfly.test.integration.elytron.oidc.client.OidcBaseTest;
import org.wildfly.test.integration.elytron.oidc.client.propagation.base.WhoAmIBean;
import org.wildfly.test.integration.elytron.oidc.client.propagation.local.AnotherEntryBeanLocal;
import org.wildfly.test.integration.elytron.oidc.client.propagation.local.AnotherEntryLocal;
import org.wildfly.test.integration.elytron.oidc.client.propagation.local.AnotherSimpleServletLocal;
import org.wildfly.test.integration.elytron.oidc.client.propagation.local.ComplexServletLocal;
import org.wildfly.test.integration.elytron.oidc.client.propagation.local.EntryBeanLocal;
import org.wildfly.test.integration.elytron.oidc.client.propagation.local.EntryLocal;
import org.wildfly.test.integration.elytron.oidc.client.propagation.local.ManagementBeanLocal;
import org.wildfly.test.integration.elytron.oidc.client.propagation.local.ServletOnlyLocal;
import org.wildfly.test.integration.elytron.oidc.client.propagation.local.SimpleServletLocal;
import org.wildfly.test.integration.elytron.oidc.client.propagation.local.WhoAmIBeanLocal;
import org.wildfly.test.integration.elytron.oidc.client.propagation.local.WhoAmILocal;
import org.wildfly.test.integration.elytron.oidc.client.propagation.remote.ComplexServletRemote;
import org.wildfly.test.integration.elytron.oidc.client.propagation.remote.EntryBeanRemote;
import org.wildfly.test.integration.elytron.oidc.client.propagation.remote.EntryRemote;
import org.wildfly.test.integration.elytron.oidc.client.propagation.remote.ManagementBeanRemote;
import org.wildfly.test.integration.elytron.oidc.client.propagation.remote.ServletOnlyRemote;
import org.wildfly.test.integration.elytron.oidc.client.propagation.remote.SimpleServletRemote;
import org.wildfly.test.integration.elytron.oidc.client.propagation.remote.WhoAmIBeanRemote;
import org.wildfly.test.integration.elytron.oidc.client.propagation.remote.WhoAmIRemote;
import org.wildfly.test.security.common.elytron.EjbElytronDomainSetup;
import org.wildfly.test.security.common.elytron.ElytronDomainSetup;
import io.restassured.RestAssured;
/**
* Test class to hold the identity propagation scenarios involving a virtual security domain with OpenID Connect.
*
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ OidcIdentityPropagationTestCase.EJBDomainSetupOverride.class, OidcIdentityPropagationTestCase.AnotherEJBDomainSetupOverride.class, OidcIdentityPropagationTestCase.PropagationSetup.class, OidcIdentityPropagationTestCase.KeycloakAndSubsystemSetup.class })
public class OidcIdentityPropagationTestCase {
private static final String TEST_REALM = "WildFly";
private static final int CLIENT_PORT = TestSuiteEnvironment.getHttpPort();
private static final String CLIENT_HOST_NAME = TestSuiteEnvironment.getHttpAddress();
private static final String CLIENT_SECRET = "secret";
private static final String OIDC_PROVIDER_URL = "oidc.provider.url";
private static final String SINGLE_DEPLOYMENT_LOCAL = "single-deployment-local";
private static final String ANOTHER_SINGLE_DEPLOYMENT_LOCAL = "another-single-deployment-local";
private static final String NO_OUTFLOW_CONFIG = "no-outflow-config";
private static final String OUTFLOW_ANONYMOUS_CONFIG = "outflow-anonymous-config";
private static final String EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_LOCAL = "ear-servlet-ejb-deployment-local";
private static final String EAR_DEPLOYMENT_WITH_SERVLET_REMOTE = "ear-servlet-remote";
private static final String EAR_DEPLOYMENT_WITH_SERVLET_LOCAL = "ear-servlet-local";
private static final String SINGLE_DEPLOYMENT_REMOTE = "single-deployment-remote";
private static final String EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE = "ear-servlet-ejb-deployment-remote";
private static final String EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE_SAME_DOMAIN = "ear-servlet-ejb-deployment-remote-same-domain";
private static final String EAR_DEPLOYMENT_WITH_EJB_LOCAL = "ear-ejb-deployment-local";
private static final String EAR_DEPLOYMENT_WITH_EJB_REMOTE = "ear-ejb-deployment-remote";
private static final String EAR_DEPLOYMENT_WITH_EJB_REMOTE_SAME_DOMAIN = "ear-ejb-deployment-remote-same-domain";
private static final String EJB_SECURITY_DOMAIN_NAME = "ejb-domain";
private static final String ANOTHER_EJB_SECURITY_DOMAIN_NAME = "another-ejb-domain";
private static final String SECURE_DEPLOYMENT_ADDRESS = "subsystem=" + ElytronOidcExtension.SUBSYSTEM_NAME + "/secure-deployment=";
private static final String PROVIDER_ADDRESS = "subsystem=" + ElytronOidcExtension.SUBSYSTEM_NAME + "/provider=";
private static final String KEYCLOAK_PROVIDER = "keycloak";
private static Map<String, KeycloakConfiguration.ClientAppType> CLIENT_IDS;
static {
CLIENT_IDS = new HashMap<>();
CLIENT_IDS.put(SINGLE_DEPLOYMENT_LOCAL + "-web", KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
CLIENT_IDS.put(ANOTHER_SINGLE_DEPLOYMENT_LOCAL + "-web", KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
CLIENT_IDS.put(NO_OUTFLOW_CONFIG + "-web", KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
CLIENT_IDS.put(OUTFLOW_ANONYMOUS_CONFIG + "-web", KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
CLIENT_IDS.put(EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_LOCAL + "-web", KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
CLIENT_IDS.put(EAR_DEPLOYMENT_WITH_SERVLET_REMOTE + "-web", KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
CLIENT_IDS.put(EAR_DEPLOYMENT_WITH_SERVLET_LOCAL + "-web", KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
CLIENT_IDS.put(SINGLE_DEPLOYMENT_REMOTE + "-web", KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
CLIENT_IDS.put(EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE + "-web", KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
CLIENT_IDS.put(EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE_SAME_DOMAIN + "-web", KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
}
private static ArrayList<String> APP_NAMES = new ArrayList<>(Arrays.asList(SINGLE_DEPLOYMENT_LOCAL, ANOTHER_SINGLE_DEPLOYMENT_LOCAL, OUTFLOW_ANONYMOUS_CONFIG, EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_LOCAL,
EAR_DEPLOYMENT_WITH_SERVLET_REMOTE, EAR_DEPLOYMENT_WITH_SERVLET_LOCAL, SINGLE_DEPLOYMENT_REMOTE, EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE, EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE_SAME_DOMAIN));
@ArquillianResource
private URL url;
@ArquillianResource
protected static Deployer deployer;
@Deployment(name= EAR_DEPLOYMENT_WITH_EJB_LOCAL, order = 1)
public static Archive<?> ejbDeploymentLocal() {
final Package currentPackage = OidcIdentityPropagationTestCase.class.getPackage();
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, EAR_DEPLOYMENT_WITH_EJB_LOCAL + "-ejb.jar")
.addClass(WhoAmIBeanLocal.class).addClass(EntryBeanLocal.class)
.addClass(WhoAmILocal.class).addClass(EntryLocal.class)
.addClass(WhoAmIBean.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml");
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_WITH_EJB_LOCAL + ".ear");
ear.addAsModule(jar);
return ear;
}
@Deployment(name= EAR_DEPLOYMENT_WITH_EJB_REMOTE, order = 2)
public static Archive<?> ejbDeploymentRemote() {
final Package currentPackage = OidcIdentityPropagationTestCase.class.getPackage();
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, EAR_DEPLOYMENT_WITH_EJB_REMOTE + "-ejb.jar")
.addClass(WhoAmIBeanRemote.class).addClass(EntryBeanRemote.class)
.addClass(WhoAmIRemote.class).addClass(EntryRemote.class)
.addClass(WhoAmIBean.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml");
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_WITH_EJB_REMOTE + ".ear");
ear.addAsModule(jar);
return ear;
}
@Deployment(name= SINGLE_DEPLOYMENT_LOCAL, order = 3)
public static Archive<?> singleDeploymentLocal() {
final String SERVER_HOST_PORT = TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort();
final Package currentPackage = OidcIdentityPropagationTestCase.class.getPackage();
final WebArchive war = ShrinkWrap.create(WebArchive.class, SINGLE_DEPLOYMENT_LOCAL + "-web.war")
.addClasses(SimpleServletLocal.class, OidcIdentityPropagationTestCase.class)
.addClass(Util.class)
.addClasses(EJBDomainSetupOverride.class, PropagationSetup.class,
AbstractMgmtTestBase.class, EjbElytronDomainSetup.class);
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, SINGLE_DEPLOYMENT_LOCAL + "-ejb.jar")
.addClass(WhoAmIBeanLocal.class).addClass(EntryBeanLocal.class)
.addClass(WhoAmILocal.class).addClass(EntryLocal.class)
.addClass(WhoAmIBean.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml");
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, SINGLE_DEPLOYMENT_LOCAL + ".ear");
ear.addAsModule(war);
ear.addAsModule(jar);
ear.addAsManifestResource(createPermissionsXmlAsset(
// Util#switchIdentity calls SecurityDomain#getCurrent and SecurityDomain#authenticate
new ElytronPermission("getSecurityDomain"),
new ElytronPermission("authenticate")
),
"permissions.xml");
return ear;
}
@Deployment(name= EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_LOCAL, order = 4)
public static Archive<?> servletAndEJBDeploymentLocal() {
final String SERVER_HOST_PORT = TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort();
final Package currentPackage = OidcIdentityPropagationTestCase.class.getPackage();
final WebArchive war = ShrinkWrap.create(WebArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_LOCAL + "-web.war")
.addClasses(ComplexServletLocal.class, OidcIdentityPropagationTestCase.class)
.addClasses(EJBDomainSetupOverride.class, PropagationSetup.class,
PropagationSetup.class, AbstractMgmtTestBase.class, EjbElytronDomainSetup.class);
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_LOCAL + "-ejb.jar")
.addClass(ManagementBeanLocal.class)
.addClass(Util.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml")
.addAsManifestResource(new StringAsset("Dependencies: deployment." + EAR_DEPLOYMENT_WITH_EJB_LOCAL + ".ear" + "." + EAR_DEPLOYMENT_WITH_EJB_LOCAL + "-ejb.jar"), "MANIFEST.MF");
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_LOCAL + ".ear");
ear.addAsModule(war);
ear.addAsModule(jar);
ear.addAsManifestResource(createPermissionsXmlAsset(
// Util#switchIdentity calls SecurityDomain#getCurrent and SecurityDomain#authenticate
new ElytronPermission("getSecurityDomain"),
new ElytronPermission("authenticate")
),
"permissions.xml");
return ear;
}
@Deployment(name= EAR_DEPLOYMENT_WITH_SERVLET_REMOTE, order = 5)
public static Archive<?> servletOnlyRemote() {
final String SERVER_HOST_PORT = TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort();
final Package currentPackage = OidcIdentityPropagationTestCase.class.getPackage();
final WebArchive war = ShrinkWrap.create(WebArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_REMOTE + "-web.war")
.addClasses(ServletOnlyRemote.class, OidcIdentityPropagationTestCase.class)
.addClasses(EJBDomainSetupOverride.class, PropagationSetup.class,
AbstractMgmtTestBase.class, EjbElytronDomainSetup.class);
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_REMOTE + "-ejb.jar")
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml")
.addAsManifestResource(new StringAsset("Dependencies: deployment." + EAR_DEPLOYMENT_WITH_EJB_REMOTE + ".ear" + "." + EAR_DEPLOYMENT_WITH_EJB_REMOTE + "-ejb.jar"), "MANIFEST.MF");
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_REMOTE + ".ear");
ear.addAsModule(war);
ear.addAsModule(jar);
ear.addAsManifestResource(createPermissionsXmlAsset(
// Util#switchIdentity calls SecurityDomain#getCurrent and SecurityDomain#authenticate
new ElytronPermission("getSecurityDomain"),
new ElytronPermission("authenticate")
),
"permissions.xml");
return ear;
}
@Deployment(name= EAR_DEPLOYMENT_WITH_SERVLET_LOCAL, order = 6)
public static Archive<?> servletOnlyLocal() {
final String SERVER_HOST_PORT = TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort();
final Package currentPackage = OidcIdentityPropagationTestCase.class.getPackage();
final WebArchive war = ShrinkWrap.create(WebArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_LOCAL + "-web.war")
.addClasses(ServletOnlyLocal.class, OidcIdentityPropagationTestCase.class)
.addClasses(EJBDomainSetupOverride.class, PropagationSetup.class,
AbstractMgmtTestBase.class, EjbElytronDomainSetup.class);
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_LOCAL + "-ejb.jar")
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml")
.addAsManifestResource(new StringAsset("Dependencies: deployment." + EAR_DEPLOYMENT_WITH_EJB_LOCAL + ".ear" + "." + EAR_DEPLOYMENT_WITH_EJB_LOCAL + "-ejb.jar"), "MANIFEST.MF");
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_LOCAL + ".ear");
ear.addAsModule(war);
ear.addAsModule(jar);
ear.addAsManifestResource(createPermissionsXmlAsset(
// Util#switchIdentity calls SecurityDomain#getCurrent and SecurityDomain#authenticate
new ElytronPermission("getSecurityDomain"),
new ElytronPermission("authenticate")
),
"permissions.xml");
return ear;
}
@Deployment(name= SINGLE_DEPLOYMENT_REMOTE, order = 7)
public static Archive<?> singleDeploymentRemote() {
final String SERVER_HOST_PORT = TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort();
final Package currentPackage = OidcIdentityPropagationTestCase.class.getPackage();
final WebArchive war = ShrinkWrap.create(WebArchive.class, SINGLE_DEPLOYMENT_REMOTE + "-web.war")
.addClasses(SimpleServletRemote.class, OidcIdentityPropagationTestCase.class)
.addClass(Util.class)
.addClasses(EJBDomainSetupOverride.class, PropagationSetup.class,
AbstractMgmtTestBase.class, EjbElytronDomainSetup.class);
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, SINGLE_DEPLOYMENT_REMOTE + "-ejb.jar")
.addClass(WhoAmIBeanRemote.class).addClass(EntryBeanRemote.class)
.addClass(WhoAmIRemote.class).addClass(EntryRemote.class)
.addClass(WhoAmIBean.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml");
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, SINGLE_DEPLOYMENT_REMOTE + ".ear");
ear.addAsModule(war);
ear.addAsModule(jar);
ear.addAsManifestResource(createPermissionsXmlAsset(
// Util#switchIdentity calls SecurityDomain#getCurrent and SecurityDomain#authenticate
new ElytronPermission("getSecurityDomain"),
new ElytronPermission("authenticate")
),
"permissions.xml");
return ear;
}
@Deployment(name= EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE, order = 8)
public static Archive<?> servletAndEJBDeploymentRemote() {
final String SERVER_HOST_PORT = TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort();
final Package currentPackage = OidcIdentityPropagationTestCase.class.getPackage();
final WebArchive war = ShrinkWrap.create(WebArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE + "-web.war")
.addClasses(ComplexServletRemote.class, OidcIdentityPropagationTestCase.class)
.addClasses(EJBDomainSetupOverride.class, PropagationSetup.class,
PropagationSetup.class, AbstractMgmtTestBase.class, EjbElytronDomainSetup.class);
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE + "-ejb.jar")
.addClass(ManagementBeanRemote.class)
.addClass(Util.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml")
.addAsManifestResource(new StringAsset("Dependencies: deployment." + EAR_DEPLOYMENT_WITH_EJB_REMOTE + ".ear" + "." + EAR_DEPLOYMENT_WITH_EJB_REMOTE + "-ejb.jar"), "MANIFEST.MF");
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE + ".ear");
ear.addAsModule(war);
ear.addAsModule(jar);
ear.addAsManifestResource(createPermissionsXmlAsset(
// Util#switchIdentity calls SecurityDomain#getCurrent and SecurityDomain#authenticate
new ElytronPermission("getSecurityDomain"),
new ElytronPermission("authenticate")
),
"permissions.xml");
return ear;
}
@Deployment(name= ANOTHER_SINGLE_DEPLOYMENT_LOCAL, order = 9)
public static Archive<?> anotherSingleDeploymentLocal() {
final String SERVER_HOST_PORT = TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort();
final Package currentPackage = OidcIdentityPropagationTestCase.class.getPackage();
final WebArchive war = ShrinkWrap.create(WebArchive.class, ANOTHER_SINGLE_DEPLOYMENT_LOCAL + "-web.war")
.addClasses(AnotherSimpleServletLocal.class, OidcIdentityPropagationTestCase.class)
.addClass(Util.class)
.addClasses(EJBDomainSetupOverride.class, AnotherEJBDomainSetupOverride.class, PropagationSetup.class,
AbstractMgmtTestBase.class, EjbElytronDomainSetup.class);
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ANOTHER_SINGLE_DEPLOYMENT_LOCAL + "-ejb.jar")
.addClass(AnotherEntryBeanLocal.class)
.addClass(AnotherEntryLocal.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml");
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, ANOTHER_SINGLE_DEPLOYMENT_LOCAL + ".ear");
ear.addAsModule(war);
ear.addAsModule(jar);
ear.addAsManifestResource(createPermissionsXmlAsset(
// Util#switchIdentity calls SecurityDomain#getCurrent and SecurityDomain#authenticate
new ElytronPermission("getSecurityDomain"),
new ElytronPermission("authenticate")
),
"permissions.xml");
return ear;
}
@Deployment(name= NO_OUTFLOW_CONFIG, order = 10)
public static Archive<?> noOutflowConfig() {
final String SERVER_HOST_PORT = TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort();
final Package currentPackage = OidcIdentityPropagationTestCase.class.getPackage();
final WebArchive war = ShrinkWrap.create(WebArchive.class, NO_OUTFLOW_CONFIG + "-web.war")
.addClasses(SimpleServletLocal.class, OidcIdentityPropagationTestCase.class)
.addClass(Util.class)
.addClasses(EJBDomainSetupOverride.class, PropagationSetup.class,
AbstractMgmtTestBase.class, EjbElytronDomainSetup.class);
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, NO_OUTFLOW_CONFIG + "-ejb.jar")
.addClass(WhoAmIBeanLocal.class).addClass(EntryBeanLocal.class)
.addClass(WhoAmILocal.class).addClass(EntryLocal.class)
.addClass(WhoAmIBean.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml");
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, NO_OUTFLOW_CONFIG + ".ear");
ear.addAsModule(war);
ear.addAsModule(jar);
ear.addAsManifestResource(createPermissionsXmlAsset(
// Util#switchIdentity calls SecurityDomain#getCurrent and SecurityDomain#authenticate
new ElytronPermission("getSecurityDomain"),
new ElytronPermission("authenticate")
),
"permissions.xml");
return ear;
}
@Deployment(name= OUTFLOW_ANONYMOUS_CONFIG, order = 11)
public static Archive<?> outflowAnonymousConfig() {
final String SERVER_HOST_PORT = TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort();
final Package currentPackage = OidcIdentityPropagationTestCase.class.getPackage();
final WebArchive war = ShrinkWrap.create(WebArchive.class, OUTFLOW_ANONYMOUS_CONFIG + "-web.war")
.addClasses(SimpleServletLocal.class, OidcIdentityPropagationTestCase.class)
.addClass(Util.class)
.addClasses(EJBDomainSetupOverride.class, PropagationSetup.class,
AbstractMgmtTestBase.class, EjbElytronDomainSetup.class);
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, OUTFLOW_ANONYMOUS_CONFIG + "-ejb.jar")
.addClass(WhoAmIBeanLocal.class).addClass(EntryBeanLocal.class)
.addClass(WhoAmILocal.class).addClass(EntryLocal.class)
.addClass(WhoAmIBean.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml");
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, OUTFLOW_ANONYMOUS_CONFIG + ".ear");
ear.addAsModule(war);
ear.addAsModule(jar);
ear.addAsManifestResource(createPermissionsXmlAsset(
// Util#switchIdentity calls SecurityDomain#getCurrent and SecurityDomain#authenticate
new ElytronPermission("getSecurityDomain"),
new ElytronPermission("authenticate")
),
"permissions.xml");
return ear;
}
@Deployment(name= EAR_DEPLOYMENT_WITH_EJB_REMOTE_SAME_DOMAIN, order = 12)
public static Archive<?> ejbDeploymentRemoteSameDomain() {
final Package currentPackage = OidcIdentityPropagationTestCase.class.getPackage();
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, EAR_DEPLOYMENT_WITH_EJB_REMOTE_SAME_DOMAIN + "-ejb.jar")
.addClass(org.wildfly.test.integration.elytron.oidc.client.propagation.annotation.WhoAmIBeanRemote.class)
.addClass(org.wildfly.test.integration.elytron.oidc.client.propagation.annotation.EntryBeanRemote.class)
.addClass(org.wildfly.test.integration.elytron.oidc.client.propagation.annotation.WhoAmIRemote.class)
.addClass(org.wildfly.test.integration.elytron.oidc.client.propagation.annotation.EntryRemote.class)
.addClass(WhoAmIBean.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml");
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_WITH_EJB_REMOTE_SAME_DOMAIN + ".ear");
ear.addAsModule(jar);
return ear;
}
@Deployment(name= EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE_SAME_DOMAIN, order = 13)
public static Archive<?> servletAndEJBDeploymentRemoteSameDomain() {
final String SERVER_HOST_PORT = TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort();
final Package currentPackage = OidcIdentityPropagationTestCase.class.getPackage();
final WebArchive war = ShrinkWrap.create(WebArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE_SAME_DOMAIN + "-web.war")
.addClasses(org.wildfly.test.integration.elytron.oidc.client.propagation.annotation.ComplexServletRemote.class, OidcIdentityPropagationTestCase.class)
.addClasses(EJBDomainSetupOverride.class, PropagationSetup.class,
PropagationSetup.class, AbstractMgmtTestBase.class, EjbElytronDomainSetup.class);
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE_SAME_DOMAIN + "-ejb.jar")
.addClass(org.wildfly.test.integration.elytron.oidc.client.propagation.annotation.ManagementBeanRemote.class)
.addClass(Util.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml")
.addAsManifestResource(new StringAsset("Dependencies: deployment." + EAR_DEPLOYMENT_WITH_EJB_REMOTE_SAME_DOMAIN + ".ear" + "." + EAR_DEPLOYMENT_WITH_EJB_REMOTE_SAME_DOMAIN + "-ejb.jar"), "MANIFEST.MF");
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE_SAME_DOMAIN + ".ear");
ear.addAsModule(war);
ear.addAsModule(jar);
ear.addAsManifestResource(createPermissionsXmlAsset(
// Util#switchIdentity calls SecurityDomain#getCurrent and SecurityDomain#authenticate
new ElytronPermission("getSecurityDomain"),
new ElytronPermission("authenticate")
),
"permissions.xml");
return ear;
}
@BeforeClass
public static void checkDockerAvailability() {
assumeTrue("Docker isn't available, OIDC tests will be skipped", isDockerAvailable());
}
private static boolean isDockerAvailable() {
try {
DockerClientFactory.instance().client();
return true;
} catch (Throwable ex) {
return false;
}
}
/**
* Servlet -> EJB propagation scenarios involving different security domains within a single deployment.
*/
/**
* The EAR used in this test case contains:
* - a servlet within a WAR
* - a local EJB within a JAR
*
* The servlet attempts to invoke the local EJB.
*/
@Test
@OperateOnDeployment(SINGLE_DEPLOYMENT_LOCAL)
public void testServletToEjbSingleDeploymentLocal() throws Exception {
testServletToEjbInvocation();
}
/**
* The EAR used in this test case contains:
* - a servlet within a WAR
* - a remote EJB within a JAR
*
* The servlet attempts to invoke the remote EJB.
*/
@Test
@OperateOnDeployment(SINGLE_DEPLOYMENT_REMOTE)
public void testServletToEjbSingleDeploymentRemote() throws Exception {
testServletToEjbInvocation();
}
/**
* The EAR used in this test case contains:
* - a servlet within a WAR
* - an EJB within a JAR
*
* The wrong password is used to access the servlet.
*/
@Test
@OperateOnDeployment(SINGLE_DEPLOYMENT_REMOTE)
public void testWrongPasswordSingleDeployment() throws Exception {
testWrongPassword();
}
private void testServletToEjbInvocation() throws Exception {
String expectedMessage = "alice,true"; // alice should have Managers role
loginToApp(KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD, HttpURLConnection.HTTP_OK, expectedMessage,
true, url.toURI().resolve("whoAmI"));
}
private void testWrongPassword() throws Exception {
loginToApp(KeycloakConfiguration.ALICE, "WRONG_PASSWORD", HttpURLConnection.HTTP_OK, "Invalid username or password", true, url.toURI().resolve("whoAmI"));
}
/**
* The EAR used in this test case contains:
* - a servlet within a WAR
* - a local EJB within a JAR
*
* The servlet attempts to invoke the local EJB.
* The identity being used to invoke the servlet doesn't exist in the security
* domain that's being used to secure the EJB.
*/
@Test
@OperateOnDeployment(SINGLE_DEPLOYMENT_LOCAL)
public void testServletToEjbSingleDeploymentOutflowNotPossibleNonExistentIdentity() throws Exception {
String expectedMessage = "anonymous,false"; // charlie won't be outflowed, the target security domain's current identity will be used instead
loginToApp(KeycloakConfiguration.CHARLIE, KeycloakConfiguration.CHARLIE_PASSWORD, HttpURLConnection.HTTP_OK, expectedMessage, true, url.toURI().resolve("whoAmI"));
}
/**
* The EAR used in this test case contains:
* - a servlet within a WAR
* - a local EJB within a JAR
*
* The servlet attempts to invoke the local EJB.
* The security domain that's being used to secure the EJB hasn't been configured to
* trust the virtual security domain.
*/
@Test
@OperateOnDeployment(ANOTHER_SINGLE_DEPLOYMENT_LOCAL)
public void testServletToEjbSingleDeploymentOutflowNotPossibleTrustNotConfigured() throws Exception {
String expectedMessage = "anonymous,false"; // charlie won't be outflowed, the target security domain's current identity will be used instead
loginToApp(KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD, HttpURLConnection.HTTP_OK, expectedMessage, true, url.toURI().resolve("anotherWhoAmI"));
}
/**
* The EAR used in this test case contains:
* - a servlet within a WAR
* - a local EJB within a JAR
*
* The servlet attempts to invoke the local EJB.
* There is no virtual security domain configuration specified.
*/
@Test
@OperateOnDeployment(NO_OUTFLOW_CONFIG)
public void testServletToEjbSingleDeploymentOutflowNotConfigured() throws Exception {
String expectedMessage = "anonymous,false"; // alice won't be outflowed, the target security domain's current identity will be used instead
loginToApp(KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD, HttpURLConnection.HTTP_OK, expectedMessage, true, url.toURI().resolve("whoAmI"));
}
/**
* The EAR used in this test case contains:
* - a servlet within a WAR
* - a local EJB within a JAR
*
* The servlet attempts to invoke the local EJB.
* outflow-anonymous has been configured for the virtual security domain that's being used to secure the servlet.
*/
@Test
@OperateOnDeployment(OUTFLOW_ANONYMOUS_CONFIG)
public void testServletToEjbSingleDeploymentOutflowAnonymousConfigured() throws Exception {
String expectedMessage = "anonymous,false"; // charlie won't be outflowed, anonymous will be used
loginToApp(KeycloakConfiguration.CHARLIE, KeycloakConfiguration.CHARLIE_PASSWORD, HttpURLConnection.HTTP_OK, expectedMessage, true, url.toURI().resolve("whoAmI"));
}
/**
* Servlet -> EJB -> EJB propagation scenarios involving different security domains across deployments.
*/
/**
* Two EARs are used in this test case.
* EAR #1 contains:
* - a servlet within a WAR
* - an EJB within a JAR
*
* EAR #2 contains:
* - a local EJB within a JAR
*
* The servlet invokes the EJB from EAR #1 and that EJB attempts to invoke the local EJB in EAR #2.
*/
@Test
@OperateOnDeployment(EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_LOCAL)
public void testEarToEarLocal() throws Exception {
testServletToEjbToEjbInvocation();
}
/**
* Two EARs are used in this test case.
* EAR #1 contains:
* - a servlet within a WAR
* - an EJB within a JAR
*
* EAR #2 contains:
* - a remote EJB within a JAR
*
* The servlet invokes the EJB from EAR #1 and that EJB attempts to invoke the remote EJB in EAR #2.
*/
@Test
@OperateOnDeployment(EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE)
public void testEarToEarRemote() throws Exception {
testServletToEjbToEjbInvocation();
}
/**
* The servlet from EAR #1 is accessed using the wrong password.
*/
@Test
@OperateOnDeployment(EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE)
public void testWrongPasswordEarToEar() throws Exception {
testWrongPassword();
}
private void testServletToEjbToEjbInvocation() throws Exception {
String expectedMessage = "alice,true"; // alice should have Managers role
loginToApp(KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD, HttpURLConnection.HTTP_OK, expectedMessage,
true, url.toURI().resolve("whoAmI"));
}
private void testServletToEjbToEjbInvocationSameDomain() throws Exception {
String expectedMessage = "alice,true,false"; // alice should have user role and not Managers role
loginToApp(KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD, HttpURLConnection.HTTP_OK, expectedMessage,
true, url.toURI().resolve("whoAmI"));
}
/**
* Two EARs are used in this test case.
* EAR #1 contains:
* - a servlet within a WAR
*
* EAR #2 contains:
* - a remote EJB within a JAR
*
* The servlet invokes the remote EJB from EAR #2.
*/
@Test
@OperateOnDeployment(EAR_DEPLOYMENT_WITH_SERVLET_REMOTE)
public void testServletToEjbEarToEarRemote() throws Exception {
testServletToEjbInvocation();
}
/**
* Two EARs are used in this test case.
* EAR #1 contains:
* - a servlet within a WAR
*
* EAR #2 contains:
* - a local EJB within a JAR
*
* The servlet invokes the local EJB from EAR #2.
*/
@Test
@OperateOnDeployment(EAR_DEPLOYMENT_WITH_SERVLET_LOCAL)
public void testServletToEjbEarToEarLocal() throws Exception {
testServletToEjbInvocation();
}
/**
* Two EARs are used in this test case.
* EAR #1 contains:
* - a servlet within a WAR
* - an EJB within a JAR
*
* EAR #2 contains:
* - a remote EJB within a JAR
*
* The servlet invokes the EJB from EAR #1 and that EJB attempts to invoke the remote EJB in EAR #2.
* The EJB in EAR #2 is secured using the same virtual security domain as EAR #1.
*/
@Test
@OperateOnDeployment(EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE_SAME_DOMAIN)
public void testEarToEarRemoteSameDomain() throws Exception {
testServletToEjbToEjbInvocationSameDomain();
}
static class EJBDomainSetupOverride extends ElytronDomainSetup {
public EJBDomainSetupOverride() {
super(new File(OidcIdentityPropagationTestCase.class.getResource("ejbusers.properties").getFile()).getAbsolutePath(),
new File(OidcIdentityPropagationTestCase.class.getResource("ejbroles.properties").getFile()).getAbsolutePath(),
EJB_SECURITY_DOMAIN_NAME);
}
}
static class AnotherEJBDomainSetupOverride extends ElytronDomainSetup {
public AnotherEJBDomainSetupOverride() {
super(new File(OidcIdentityPropagationTestCase.class.getResource("ejbusers.properties").getFile()).getAbsolutePath(),
new File(OidcIdentityPropagationTestCase.class.getResource("ejbroles.properties").getFile()).getAbsolutePath(),
ANOTHER_EJB_SECURITY_DOMAIN_NAME);
}
}
static class PropagationSetup extends AbstractMgmtTestBase implements ServerSetupTask {
private ManagementClient managementClient;
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
this.managementClient = managementClient;
final List<ModelNode> updates = new ArrayList<ModelNode>();
updates.add(getAddEjbApplicationSecurityDomainOp(EJB_SECURITY_DOMAIN_NAME, EJB_SECURITY_DOMAIN_NAME));
updates.add(getAddEjbApplicationSecurityDomainOp(ANOTHER_EJB_SECURITY_DOMAIN_NAME, ANOTHER_EJB_SECURITY_DOMAIN_NAME));
// /subsystem=elytron/virtual-security-domain=APP_NAME:add(outflow-security-domains=["ejb-domain"])
// /subsystem=elytron/virtual-security-domain=another-single-deployment-local:add(outflow-security-domains=["another-ejb-domain"])
for (String app : APP_NAMES) {
updates.add(getAddVirtualSecurityDomainOp(app, app.equals(ANOTHER_SINGLE_DEPLOYMENT_LOCAL) ? ANOTHER_EJB_SECURITY_DOMAIN_NAME : EJB_SECURITY_DOMAIN_NAME));
}
// /subsystem=elytron/virtual-security-domain=outflow-anonymous-config.ear:write-attribute(name=outflow-anonymous, value=true)
ModelNode op = new ModelNode();
op.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
op.get(OP_ADDR).add(SUBSYSTEM, "elytron");
op.get(OP_ADDR).add("virtual-security-domain", OUTFLOW_ANONYMOUS_CONFIG + ".ear");
op.get("name").set("outflow-anonymous");
op.get("value").set(true);
updates.add(op);
// /subsystem=elytron/security-domain=ejb-domain:write-attribute(name=trusted-virtual-security-domains, value=["APP_NAMES"])
op = new ModelNode();
op.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
op.get(OP_ADDR).add(SUBSYSTEM, "elytron");
op.get(OP_ADDR).add("security-domain", EJB_SECURITY_DOMAIN_NAME);
op.get("name").set("trusted-virtual-security-domains");
ModelNode trustedDomains = new ModelNode();
for (String app : APP_NAMES) {
trustedDomains.add(app + ".ear");
}
op.get("value").set(trustedDomains);
updates.add(op);
executeOperations(updates);
ServerReload.executeReloadAndWaitForCompletion(managementClient, 50000);
}
@Override
public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception {
final List<ModelNode> updates = new ArrayList<>();
ModelNode op = ModelUtil.createOpNode(
"subsystem=ejb3/application-security-domain=" + EJB_SECURITY_DOMAIN_NAME, REMOVE);
updates.add(op);
op = ModelUtil.createOpNode(
"subsystem=ejb3/application-security-domain=" + ANOTHER_EJB_SECURITY_DOMAIN_NAME, REMOVE);
updates.add(op);
for (String app : APP_NAMES) {
op = ModelUtil.createOpNode(
"subsystem=elytron/virtual-security-domain=" + app + ".ear", REMOVE);
updates.add(op);
}
executeOperations(updates);
ServerReload.executeReloadAndWaitForCompletion(managementClient, 50000);
}
@Override
protected ModelControllerClient getModelControllerClient() {
return managementClient.getControllerClient();
}
private static PathAddress getEjbApplicationSecurityDomainAddress(String ejbDomainName) {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "ejb3")
.append("application-security-domain", ejbDomainName);
}
private static ModelNode getAddEjbApplicationSecurityDomainOp(String ejbDomainName, String securityDomainName) {
ModelNode op = createAddOperation(getEjbApplicationSecurityDomainAddress(ejbDomainName));
op.get("security-domain").set(securityDomainName);
return op;
}
}
static class KeycloakAndSubsystemSetup extends OidcBaseTest.KeycloakSetup {
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
super.setup(managementClient, containerId);
OidcBaseTest.sendRealmCreationRequest(getRealmRepresentation(TEST_REALM, CLIENT_SECRET, CLIENT_HOST_NAME, CLIENT_PORT, CLIENT_IDS));
ModelControllerClient client = managementClient.getControllerClient();
ModelNode operation = createOpNode("system-property=" + OIDC_PROVIDER_URL, ModelDescriptionConstants.ADD);
operation.get("value").set(KEYCLOAK_CONTAINER.getAuthServerUrl() + "/realms/" + TEST_REALM);
Utils.applyUpdate(operation, client);
client = managementClient.getControllerClient();
operation = createOpNode(PROVIDER_ADDRESS + KEYCLOAK_PROVIDER , ModelDescriptionConstants.ADD);
operation.get("provider-url").set(KEYCLOAK_CONTAINER.getAuthServerUrl() + "/realms/" + TEST_REALM);
Utils.applyUpdate(operation, client);
for (String app : CLIENT_IDS.keySet()) {
operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + app + ".war", ModelDescriptionConstants.ADD);
operation.get("client-id").set(app);
operation.get("public-client").set(false);
operation.get("provider").set(KEYCLOAK_PROVIDER);
operation.get("ssl-required").set("EXTERNAL");
operation.get("principal-attribute").set("preferred_username");
Utils.applyUpdate(operation, client);
operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + app + ".war/credential=secret", ModelDescriptionConstants.ADD);
operation.get("secret").set("secret");
Utils.applyUpdate(operation, client);
}
ServerReload.executeReloadAndWaitForCompletion(managementClient);
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
ModelControllerClient client = managementClient.getControllerClient();
ModelNode operation = createOpNode("system-property=" + OIDC_PROVIDER_URL, ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, client);
for (String appName : CLIENT_IDS.keySet()) {
removeSecureDeployment(client, appName);
}
removeProvider(client, KEYCLOAK_PROVIDER);
RestAssured
.given()
.auth().oauth2(org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.getAdminAccessToken(KEYCLOAK_CONTAINER.getAuthServerUrl()))
.when()
.delete(KEYCLOAK_CONTAINER.getAuthServerUrl() + "/admin/realms/" + TEST_REALM).then().statusCode(204);
super.tearDown(managementClient, containerId);
}
}
private static void removeSecureDeployment(ModelControllerClient client, String name) throws Exception {
ModelNode operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + name + ".war", ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, client);
}
private static void removeProvider(ModelControllerClient client, String provider) throws Exception {
ModelNode operation = createOpNode(PROVIDER_ADDRESS + provider, ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, client);
}
private static PathAddress getVirtualSecurityDomainAddress(String virtualSecurityDomainName) {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "elytron")
.append("virtual-security-domain", virtualSecurityDomainName + ".ear");
}
private static ModelNode getAddVirtualSecurityDomainOp(String virtualSecurityDomainName, String... outflowDomains) {
ModelNode op = createAddOperation(getVirtualSecurityDomainAddress(virtualSecurityDomainName));
if (! virtualSecurityDomainName.equals(EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE_SAME_DOMAIN)) {
ModelNode outflowSecurityDomains = new ModelNode();
for (String outflowSecurityDomain : outflowDomains) {
outflowSecurityDomains.add(outflowSecurityDomain);
}
op.get("outflow-security-domains").set(outflowSecurityDomains);
}
return op;
}
}
| 50,223
| 55.178971
| 268
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/remote/ServletOnlyRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.remote;
import static org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.JBOSS_ADMIN_ROLE;
import java.io.IOException;
import java.io.Writer;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jakarta.annotation.security.DeclareRoles;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HttpConstraint;
import jakarta.servlet.annotation.ServletSecurity;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@WebServlet(urlPatterns = "/whoAmI", loadOnStartup = 1)
@ServletSecurity(@HttpConstraint(rolesAllowed = { JBOSS_ADMIN_ROLE }))
@DeclareRoles(JBOSS_ADMIN_ROLE)
public class ServletOnlyRemote extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
Writer writer = resp.getWriter();
try {
EntryRemote bean = lookup(EntryRemote.class, "java:global/ear-ejb-deployment-remote/ear-ejb-deployment-remote-ejb/EntryBeanRemote!org.wildfly.test.integration.elytron.oidc.client.propagation.remote.EntryRemote");
writer.write(bean.whoAmI() + "," + String.valueOf(bean.doIHaveRole("Managers")));
} catch (Exception e) {
throw new ServletException("Unexpected Failure", e);
}
}
public static <T> T lookup(Class<T> clazz, String jndiName) {
Object bean = lookup(jndiName);
return clazz.cast(bean);
}
private static Object lookup(String jndiName) {
Context context = null;
try {
context = new InitialContext();
return context.lookup(jndiName);
} catch (NamingException ex) {
throw new IllegalStateException(ex);
} finally {
try {
context.close();
} catch (NamingException ex) {
throw new IllegalStateException(ex);
}
}
}
}
| 3,356
| 38.034884
| 224
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/remote/EntryBeanRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.remote;
import jakarta.annotation.Resource;
import jakarta.ejb.EJB;
import jakarta.ejb.SessionContext;
import jakarta.ejb.Stateless;
import org.jboss.ejb3.annotation.SecurityDomain;
/**
* Concrete implementation to allow deployment of bean.
*
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@Stateless
@SecurityDomain("ejb-domain")
public class EntryBeanRemote implements EntryRemote {
@EJB
private WhoAmIRemote whoAmIBean;
@Resource
private SessionContext context;
public String whoAmI() {
return context.getCallerPrincipal().getName();
}
public boolean doIHaveRole(String roleName) {
return context.isCallerInRole(roleName);
}
}
| 1,802
| 31.196429
| 76
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/remote/SimpleServletRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.remote;
import static org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.JBOSS_ADMIN_ROLE;
import java.io.IOException;
import java.io.Writer;
import jakarta.annotation.security.DeclareRoles;
import jakarta.ejb.EJB;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HttpConstraint;
import jakarta.servlet.annotation.ServletSecurity;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@WebServlet(urlPatterns = "/whoAmI", loadOnStartup = 1)
@ServletSecurity(@HttpConstraint(rolesAllowed = { JBOSS_ADMIN_ROLE }))
@DeclareRoles(JBOSS_ADMIN_ROLE)
public class SimpleServletRemote extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
private EntryRemote bean;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
Writer writer = resp.getWriter();
try {
writer.write(bean.whoAmI() + "," + String.valueOf(bean.doIHaveRole("Managers")));
} catch (Exception e) {
throw new ServletException("Unexpected Failure", e);
}
}
}
| 2,476
| 37.107692
| 113
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/remote/ManagementBeanRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.remote;
import static org.jboss.as.test.shared.integration.ejb.security.Util.switchIdentity;
import java.util.concurrent.Callable;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.ejb.SessionContext;
import jakarta.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/**
* A simple EJB that can be called to obtain the current caller principal and to check the role membership for
* that principal.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@Stateless
public class ManagementBeanRemote {
@Resource
private SessionContext context;
@PermitAll
public String whoAmI() {
return context.getCallerPrincipal().getName();
}
@PermitAll
public boolean invokeEntryDoIHaveRole(String role) {
EntryRemote entry = lookup(EntryRemote.class, "java:global/ear-ejb-deployment-remote/ear-ejb-deployment-remote-ejb/EntryBeanRemote!org.wildfly.test.integration.elytron.oidc.client.propagation.remote.EntryRemote");
return entry.doIHaveRole(role);
}
@PermitAll
public String[] switchThenInvokeEntryDoIHaveRole(String username, String password, String role) {
EntryRemote entry = lookup(EntryRemote.class, "java:global/ear-ejb-deployment-remote/ear-ejb-deployment-remote-ejb/EntryBeanRemote!org.wildfly.test.integration.elytron.oidc.client.propagation.remote.EntryRemote");
final Callable<String[]> callable = () -> {
String remoteWho = entry.whoAmI();
boolean hasRole = entry.doIHaveRole(role);
return new String[] { remoteWho, String.valueOf(hasRole) };
};
try {
return switchIdentity(username, password, callable);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public static <T> T lookup(Class<T> clazz, String jndiName) {
Object bean = lookup(jndiName);
return clazz.cast(bean);
}
private static Object lookup(String jndiName) {
Context context = null;
try {
context = new InitialContext();
return context.lookup(jndiName);
} catch (NamingException ex) {
throw new IllegalStateException(ex);
} finally {
try {
context.close();
} catch (NamingException ex) {
throw new IllegalStateException(ex);
}
}
}
}
| 3,615
| 37.063158
| 221
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/remote/WhoAmIRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.remote;
import java.security.Principal;
import jakarta.ejb.Remote;
/**
* The local interface to the simple WhoAmI bean.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@Remote
public interface WhoAmIRemote {
/**
* @return the caller principal obtained from the EJBContext.
*/
Principal getCallerPrincipal();
/**
* @param roleName - The role to check.
* @return The result of calling EJBContext.isCallerInRole() with the supplied role name.
*/
boolean doIHaveRole(String roleName);
}
| 1,661
| 34.361702
| 93
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/remote/WhoAmIBeanRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.remote;
import jakarta.ejb.Stateless;
import org.jboss.ejb3.annotation.SecurityDomain;
import org.wildfly.test.integration.elytron.oidc.client.propagation.base.WhoAmIBean;
/**
* Concrete implementation to allow deployment of bean.
*
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@Stateless
@SecurityDomain("ejb-domain")
public class WhoAmIBeanRemote extends WhoAmIBean implements WhoAmIRemote {
}
| 1,516
| 38.921053
| 84
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/remote/EntryRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.remote;
import jakarta.ejb.Remote;
/**
* Interface for the bean used as the entry point to verify Enterprise Beans 3 security behaviour.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@Remote
public interface EntryRemote {
/**
* @return The name of the Principal obtained from a call to EJBContext.getCallerPrincipal()
*/
String whoAmI();
/**
* @param roleName - The role to check.
* @return the response from EJBContext.isCallerInRole() with the supplied role name.
*/
boolean doIHaveRole(String roleName);
}
| 1,689
| 35.73913
| 98
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/remote/ComplexServletRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.remote;
import static org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.JBOSS_ADMIN_ROLE;
import java.io.IOException;
import java.io.Writer;
import jakarta.annotation.security.DeclareRoles;
import jakarta.ejb.EJB;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HttpConstraint;
import jakarta.servlet.annotation.ServletSecurity;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@WebServlet(urlPatterns = "/whoAmI", loadOnStartup = 1)
@ServletSecurity(@HttpConstraint(rolesAllowed = { JBOSS_ADMIN_ROLE }))
@DeclareRoles(JBOSS_ADMIN_ROLE)
public class ComplexServletRemote extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
private ManagementBeanRemote bean;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
Writer writer = resp.getWriter();
try {
writer.write(bean.whoAmI() + "," + String.valueOf(bean.invokeEntryDoIHaveRole("Managers")));
} catch (Exception e) {
throw new ServletException("Unexpected Failure", e);
}
}
}
| 2,497
| 37.430769
| 113
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/local/SimpleServletLocal.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.local;
import static org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.JBOSS_ADMIN_ROLE;
import java.io.IOException;
import java.io.Writer;
import jakarta.annotation.security.DeclareRoles;
import jakarta.ejb.EJB;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HttpConstraint;
import jakarta.servlet.annotation.ServletSecurity;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@WebServlet(urlPatterns = "/whoAmI", loadOnStartup = 1)
@ServletSecurity(@HttpConstraint(rolesAllowed = { JBOSS_ADMIN_ROLE }))
@DeclareRoles(JBOSS_ADMIN_ROLE)
public class SimpleServletLocal extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
private EntryLocal bean;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
Writer writer = resp.getWriter();
try {
writer.write(bean.whoAmI() + "," + String.valueOf(bean.doIHaveRole("Managers")));
} catch (Exception e) {
throw new ServletException("Unexpected Failure", e);
}
}
}
| 2,472
| 37.640625
| 113
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/local/AnotherEntryLocal.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.local;
import jakarta.ejb.Local;
/**
* Interface for the bean used as the entry point to verify Enterprise Beans 3 security behaviour.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@Local
public interface AnotherEntryLocal {
/**
* @return The name of the Principal obtained from a call to EJBContext.getCallerPrincipal()
*/
String whoAmI();
/**
* @param roleName - The role to check.
* @return the response from EJBContext.isCallerInRole() with the supplied role name.
*/
boolean doIHaveRole(String roleName);
}
| 1,692
| 35.804348
| 98
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/local/WhoAmILocal.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.local;
import java.security.Principal;
import jakarta.ejb.Local;
/**
* The local interface to the simple WhoAmI bean.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@Local
public interface WhoAmILocal {
/**
* @return the caller principal obtained from the EJBContext.
*/
Principal getCallerPrincipal();
/**
* @param roleName - The role to check.
* @return The result of calling EJBContext.isCallerInRole() with the supplied role name.
*/
boolean doIHaveRole(String roleName);
}
| 1,657
| 34.276596
| 93
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/local/ServletOnlyLocal.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.local;
import static org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.JBOSS_ADMIN_ROLE;
import java.io.IOException;
import java.io.Writer;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jakarta.annotation.security.DeclareRoles;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HttpConstraint;
import jakarta.servlet.annotation.ServletSecurity;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@WebServlet(urlPatterns = "/whoAmI", loadOnStartup = 1)
@ServletSecurity(@HttpConstraint(rolesAllowed = { JBOSS_ADMIN_ROLE }))
@DeclareRoles(JBOSS_ADMIN_ROLE)
public class ServletOnlyLocal extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
Writer writer = resp.getWriter();
try {
EntryLocal bean = lookup(EntryLocal.class, "java:global/ear-ejb-deployment-local/ear-ejb-deployment-local-ejb/EntryBeanLocal!org.wildfly.test.integration.elytron.oidc.client.propagation.local.EntryLocal");
writer.write(bean.whoAmI() + "," + String.valueOf(bean.doIHaveRole("Managers")));
} catch (Exception e) {
throw new ServletException("Unexpected Failure", e);
}
}
public static <T> T lookup(Class<T> clazz, String jndiName) {
Object bean = lookup(jndiName);
return clazz.cast(bean);
}
private static Object lookup(String jndiName) {
Context context = null;
try {
context = new InitialContext();
return context.lookup(jndiName);
} catch (NamingException ex) {
throw new IllegalStateException(ex);
} finally {
try {
context.close();
} catch (NamingException ex) {
throw new IllegalStateException(ex);
}
}
}
}
| 3,347
| 37.930233
| 217
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/local/ManagementBeanLocal.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.local;
import static org.jboss.as.test.shared.integration.ejb.security.Util.switchIdentity;
import java.util.concurrent.Callable;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.ejb.SessionContext;
import jakarta.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/**
* A simple EJB that can be called to obtain the current caller principal and to check the role membership for
* that principal.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@Stateless
public class ManagementBeanLocal {
@Resource
private SessionContext context;
@PermitAll
public String whoAmI() {
return context.getCallerPrincipal().getName();
}
@PermitAll
public boolean invokeEntryDoIHaveRole(String role) {
EntryLocal entry = lookup(EntryLocal.class, "java:global/ear-ejb-deployment-local/ear-ejb-deployment-local-ejb/EntryBeanLocal!org.wildfly.test.integration.elytron.oidc.client.propagation.local.EntryLocal");
return entry.doIHaveRole(role);
}
@PermitAll
public String[] switchThenInvokeEntryDoIHaveRole(String username, String password, String role) {
EntryLocal entry = lookup(EntryLocal.class, "java:global/ear-ejb-deployment-local/ear-ejb-deployment-local-ejb/EntryBeanLocal!org.wildfly.test.integration.elytron.oidc.client.propagation.local.EntryLocal");
final Callable<String[]> callable = () -> {
String localWho = entry.whoAmI();
boolean hasRole = entry.doIHaveRole(role);
return new String[] { localWho, String.valueOf(hasRole) };
};
try {
return switchIdentity(username, password, callable);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public static <T> T lookup(Class<T> clazz, String jndiName) {
Object bean = lookup(jndiName);
return clazz.cast(bean);
}
private static Object lookup(String jndiName) {
Context context = null;
try {
context = new InitialContext();
return context.lookup(jndiName);
} catch (NamingException ex) {
throw new IllegalStateException(ex);
} finally {
try {
context.close();
} catch (NamingException ex) {
throw new IllegalStateException(ex);
}
}
}
}
| 3,597
| 36.873684
| 214
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/local/WhoAmIBeanLocal.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.local;
import jakarta.ejb.Stateless;
import org.jboss.ejb3.annotation.SecurityDomain;
import org.wildfly.test.integration.elytron.oidc.client.propagation.base.WhoAmIBean;
/**
* Concrete implementation to allow deployment of bean.
*
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@Stateless
@SecurityDomain("ejb-domain")
public class WhoAmIBeanLocal extends WhoAmIBean implements WhoAmILocal {
}
| 1,513
| 38.842105
| 84
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/local/AnotherEntryBeanLocal.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.local;
import org.jboss.ejb3.annotation.SecurityDomain;
import jakarta.annotation.Resource;
import jakarta.ejb.SessionContext;
import jakarta.ejb.Stateless;
/**
* Concrete implementation to allow deployment of bean.
*
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@Stateless
@SecurityDomain("another-ejb-domain")
public class AnotherEntryBeanLocal implements AnotherEntryLocal {
@Resource
private SessionContext context;
public String whoAmI() {
return context.getCallerPrincipal().getName();
}
public boolean doIHaveRole(String roleName) {
return context.isCallerInRole(roleName);
}
}
| 1,750
| 32.673077
| 75
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/local/AnotherSimpleServletLocal.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.local;
import static org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.JBOSS_ADMIN_ROLE;
import java.io.IOException;
import java.io.Writer;
import jakarta.annotation.security.DeclareRoles;
import jakarta.ejb.EJB;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HttpConstraint;
import jakarta.servlet.annotation.ServletSecurity;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@WebServlet(urlPatterns = "/anotherWhoAmI", loadOnStartup = 1)
@ServletSecurity(@HttpConstraint(rolesAllowed = { JBOSS_ADMIN_ROLE }))
@DeclareRoles(JBOSS_ADMIN_ROLE)
public class AnotherSimpleServletLocal extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
private AnotherEntryLocal bean;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
Writer writer = resp.getWriter();
try {
writer.write(bean.whoAmI() + "," + String.valueOf(bean.doIHaveRole("Managers")));
} catch (Exception e) {
throw new ServletException("Unexpected Failure", e);
}
}
}
| 2,493
| 37.96875
| 113
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/local/ComplexServletLocal.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.local;
import static org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.JBOSS_ADMIN_ROLE;
import java.io.IOException;
import java.io.Writer;
import jakarta.annotation.security.DeclareRoles;
import jakarta.ejb.EJB;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HttpConstraint;
import jakarta.servlet.annotation.ServletSecurity;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@WebServlet(urlPatterns = "/whoAmI", loadOnStartup = 1)
@ServletSecurity(@HttpConstraint(rolesAllowed = { JBOSS_ADMIN_ROLE }))
@DeclareRoles(JBOSS_ADMIN_ROLE)
public class ComplexServletLocal extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
private ManagementBeanLocal bean;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
Writer writer = resp.getWriter();
try {
writer.write(bean.whoAmI() + "," + String.valueOf(bean.invokeEntryDoIHaveRole("Managers")));
} catch (Exception e) {
throw new ServletException("Unexpected Failure", e);
}
}
}
| 2,494
| 37.384615
| 113
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/local/EntryLocal.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.local;
import jakarta.ejb.Local;
/**
* Interface for the bean used as the entry point to verify Enterprise Beans 3 security behaviour.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@Local
public interface EntryLocal {
/**
* @return The name of the Principal obtained from a call to EJBContext.getCallerPrincipal()
*/
String whoAmI();
/**
* @param roleName - The role to check.
* @return the response from EJBContext.isCallerInRole() with the supplied role name.
*/
boolean doIHaveRole(String roleName);
}
| 1,685
| 35.652174
| 98
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/local/EntryBeanLocal.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.local;
import jakarta.annotation.Resource;
import jakarta.ejb.EJB;
import jakarta.ejb.SessionContext;
import jakarta.ejb.Stateless;
import org.jboss.ejb3.annotation.SecurityDomain;
/**
* Concrete implementation to allow deployment of bean.
*
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@Stateless
@SecurityDomain("ejb-domain")
public class EntryBeanLocal implements EntryLocal {
@EJB
private WhoAmILocal whoAmIBean;
@Resource
private SessionContext context;
public String whoAmI() {
return context.getCallerPrincipal().getName();
}
public boolean doIHaveRole(String roleName) {
return context.isCallerInRole(roleName);
}
}
| 1,798
| 31.125
| 75
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/base/EntryBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.base;
import java.util.concurrent.Callable;
import jakarta.annotation.Resource;
import jakarta.ejb.EJB;
import jakarta.ejb.SessionContext;
import org.wildfly.security.auth.server.RealmUnavailableException;
import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.security.evidence.PasswordGuessEvidence;
/**
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
public abstract class EntryBean {
@EJB
private WhoAmI whoAmIBean;
@Resource
private SessionContext context;
public String whoAmI() {
return context.getCallerPrincipal().getName();
}
public String[] doubleWhoAmI() {
String localWho = context.getCallerPrincipal().getName();
String remoteWho = whoAmIBean.getCallerPrincipal().getName();
String secondLocalWho = context.getCallerPrincipal().getName();
if (secondLocalWho.equals(localWho) == false) {
throw new IllegalStateException("Local getCallerPrincipal changed from '" + localWho + "' to '" + secondLocalWho);
}
return new String[] { localWho, remoteWho };
}
public String[] doubleWhoAmI(String username, String password) throws Exception {
String localWho = context.getCallerPrincipal().getName();
final Callable<String[]> callable = () -> {
String remoteWho = whoAmIBean.getCallerPrincipal().getName();
return new String[] { localWho, remoteWho };
};
try {
return switchIdentity(username, password, callable);
} finally {
String secondLocalWho = context.getCallerPrincipal().getName();
if (secondLocalWho.equals(localWho) == false) {
throw new IllegalStateException(
"Local getCallerPrincipal changed from '" + localWho + "' to '" + secondLocalWho);
}
}
}
public boolean doIHaveRole(String roleName) {
return context.isCallerInRole(roleName);
}
public boolean[] doubleDoIHaveRole(String roleName) {
boolean localDoI = context.isCallerInRole(roleName);
boolean remoteDoI = whoAmIBean.doIHaveRole(roleName);
return new boolean[] { localDoI, remoteDoI };
}
public boolean[] doubleDoIHaveRole(String roleName, String username, String password) throws Exception {
boolean localDoI = context.isCallerInRole(roleName);
final Callable<boolean[]> callable = () -> {
boolean remoteDoI = whoAmIBean.doIHaveRole(roleName);
return new boolean[] { localDoI, remoteDoI };
};
try {
return switchIdentity(username, password, callable);
} finally {
boolean secondLocalDoI = context.isCallerInRole(roleName);
if (secondLocalDoI != localDoI) {
throw new IllegalStateException("Local call to isCallerInRole for '" + roleName + "' changed from " + localDoI
+ " to " + secondLocalDoI);
}
}
}
private static <T> T switchIdentity(final String username, final String password, final Callable<T> callable)
throws RealmUnavailableException, Exception {
return SecurityDomain.getCurrent().authenticate(username, new PasswordGuessEvidence(password.toCharArray()))
.runAs(callable);
}
}
| 4,457
| 38.451327
| 126
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/base/WhoAmIBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.base;
import java.security.Principal;
import jakarta.annotation.Resource;
import jakarta.ejb.SessionContext;
/**
* @author <a href="mailto:cdewolf@redhat.com">Carlo de Wolf</a>
*/
public abstract class WhoAmIBean {
@Resource
private SessionContext context;
public Principal getCallerPrincipal() {
return context.getCallerPrincipal();
}
public boolean doIHaveRole(String roleName) {
return context.isCallerInRole(roleName);
}
}
| 1,572
| 33.195652
| 74
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/base/WhoAmI.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.base;
import java.security.Principal;
import jakarta.ejb.Local;
/**
* The local interface to the simple WhoAmI bean.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@Local
public interface WhoAmI {
/**
* @return the caller principal obtained from the EJBContext.
*/
Principal getCallerPrincipal();
/**
* @param roleName - The role to check.
* @return The result of calling EJBContext.isCallerInRole() with the supplied role name.
*/
boolean doIHaveRole(String roleName);
}
| 1,651
| 34.148936
| 93
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/annotation/ServletOnlyRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.annotation;
import static org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.JBOSS_ADMIN_ROLE;
import java.io.IOException;
import java.io.Writer;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jakarta.annotation.security.DeclareRoles;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HttpConstraint;
import jakarta.servlet.annotation.ServletSecurity;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@WebServlet(urlPatterns = "/whoAmI", loadOnStartup = 1)
@ServletSecurity(@HttpConstraint(rolesAllowed = { JBOSS_ADMIN_ROLE }))
@DeclareRoles(JBOSS_ADMIN_ROLE)
public class ServletOnlyRemote extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
Writer writer = resp.getWriter();
try {
EntryRemote bean = lookup(EntryRemote.class, "java:global/ear-ejb-deployment-remote-same-domain/ear-ejb-deployment-remote-same-domain-ejb/EntryBeanRemote!org.wildfly.test.integration.elytron.oidc.client.propagation.annotation.EntryRemote");
writer.write(bean.whoAmI() + "," + String.valueOf(bean.doIHaveRole("Managers")));
} catch (Exception e) {
throw new ServletException("Unexpected Failure", e);
}
}
public static <T> T lookup(Class<T> clazz, String jndiName) {
Object bean = lookup(jndiName);
return clazz.cast(bean);
}
private static Object lookup(String jndiName) {
Context context = null;
try {
context = new InitialContext();
return context.lookup(jndiName);
} catch (NamingException ex) {
throw new IllegalStateException(ex);
} finally {
try {
context.close();
} catch (NamingException ex) {
throw new IllegalStateException(ex);
}
}
}
}
| 3,388
| 38.406977
| 252
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/annotation/EntryBeanRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.annotation;
import jakarta.annotation.Resource;
import jakarta.ejb.EJB;
import jakarta.ejb.SessionContext;
import jakarta.ejb.Stateless;
import org.jboss.ejb3.annotation.SecurityDomain;
/**
* Concrete implementation to allow deployment of bean.
*
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@Stateless
@SecurityDomain("ear-servlet-ejb-deployment-remote-same-domain.ear")
public class EntryBeanRemote implements EntryRemote {
@EJB
private WhoAmIRemote whoAmIBean;
@Resource
private SessionContext context;
public String whoAmI() {
return context.getCallerPrincipal().getName();
}
public boolean doIHaveRole(String roleName) {
return context.isCallerInRole(roleName);
}
}
| 1,845
| 31.964286
| 80
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/annotation/SimpleServletRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.annotation;
import static org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.JBOSS_ADMIN_ROLE;
import java.io.IOException;
import java.io.Writer;
import jakarta.annotation.security.DeclareRoles;
import jakarta.ejb.EJB;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HttpConstraint;
import jakarta.servlet.annotation.ServletSecurity;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@WebServlet(urlPatterns = "/whoAmI", loadOnStartup = 1)
@ServletSecurity(@HttpConstraint(rolesAllowed = { JBOSS_ADMIN_ROLE }))
@DeclareRoles(JBOSS_ADMIN_ROLE)
public class SimpleServletRemote extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
private EntryRemote bean;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
Writer writer = resp.getWriter();
try {
writer.write(bean.whoAmI() + "," + String.valueOf(bean.doIHaveRole("Managers")));
} catch (Exception e) {
throw new ServletException("Unexpected Failure", e);
}
}
}
| 2,480
| 37.169231
| 113
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/annotation/ManagementBeanRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.annotation;
import static org.jboss.as.test.shared.integration.ejb.security.Util.switchIdentity;
import java.util.concurrent.Callable;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.ejb.SessionContext;
import jakarta.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/**
* A simple EJB that can be called to obtain the current caller principal and to check the role membership for
* that principal.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@Stateless
public class ManagementBeanRemote {
@Resource
private SessionContext context;
@PermitAll
public String whoAmI() {
return context.getCallerPrincipal().getName();
}
@PermitAll
public boolean invokeEntryDoIHaveRole(String role) {
EntryRemote entry = lookup(EntryRemote.class, "java:global/ear-ejb-deployment-remote-same-domain/ear-ejb-deployment-remote-same-domain-ejb/EntryBeanRemote!org.wildfly.test.integration.elytron.oidc.client.propagation.annotation.EntryRemote");
return entry.doIHaveRole(role);
}
@PermitAll
public String[] switchThenInvokeEntryDoIHaveRole(String username, String password, String role) {
EntryRemote entry = lookup(EntryRemote.class, "java:global/ear-ejb-deployment-remote-same-domain/ear-ejb-deployment-remote-same-domain-ejb/EntryBeanRemote!org.wildfly.test.integration.elytron.oidc.client.propagation.annotation.EntryRemote");
final Callable<String[]> callable = () -> {
String remoteWho = entry.whoAmI();
boolean hasRole = entry.doIHaveRole(role);
return new String[] { remoteWho, String.valueOf(hasRole) };
};
try {
return switchIdentity(username, password, callable);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public static <T> T lookup(Class<T> clazz, String jndiName) {
Object bean = lookup(jndiName);
return clazz.cast(bean);
}
private static Object lookup(String jndiName) {
Context context = null;
try {
context = new InitialContext();
return context.lookup(jndiName);
} catch (NamingException ex) {
throw new IllegalStateException(ex);
} finally {
try {
context.close();
} catch (NamingException ex) {
throw new IllegalStateException(ex);
}
}
}
}
| 3,675
| 37.694737
| 249
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/annotation/WhoAmIRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.annotation;
import java.security.Principal;
import jakarta.ejb.Remote;
/**
* The local interface to the simple WhoAmI bean.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@Remote
public interface WhoAmIRemote {
/**
* @return the caller principal obtained from the EJBContext.
*/
Principal getCallerPrincipal();
/**
* @param roleName - The role to check.
* @return The result of calling EJBContext.isCallerInRole() with the supplied role name.
*/
boolean doIHaveRole(String roleName);
}
| 1,665
| 34.446809
| 93
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/annotation/WhoAmIBeanRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.annotation;
import jakarta.ejb.Stateless;
import org.jboss.ejb3.annotation.SecurityDomain;
import org.wildfly.test.integration.elytron.oidc.client.propagation.base.WhoAmIBean;
/**
* Concrete implementation to allow deployment of bean.
*
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@Stateless
@SecurityDomain("ear-servlet-ejb-deployment-remote-same-domain.ear")
public class WhoAmIBeanRemote extends WhoAmIBean implements WhoAmIRemote {
}
| 1,559
| 40.052632
| 84
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/annotation/EntryRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.annotation;
import jakarta.ejb.Remote;
/**
* Interface for the bean used as the entry point to verify Enterprise Beans 3 security behaviour.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@Remote
public interface EntryRemote {
/**
* @return The name of the Principal obtained from a call to EJBContext.getCallerPrincipal()
*/
String whoAmI();
/**
* @param roleName - The role to check.
* @return the response from EJBContext.isCallerInRole() with the supplied role name.
*/
boolean doIHaveRole(String roleName);
}
| 1,693
| 35.826087
| 98
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/propagation/annotation/ComplexServletRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.propagation.annotation;
import static org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.JBOSS_ADMIN_ROLE;
import java.io.IOException;
import java.io.Writer;
import jakarta.annotation.security.DeclareRoles;
import jakarta.ejb.EJB;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HttpConstraint;
import jakarta.servlet.annotation.ServletSecurity;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@WebServlet(urlPatterns = "/whoAmI", loadOnStartup = 1)
@ServletSecurity(@HttpConstraint(rolesAllowed = { JBOSS_ADMIN_ROLE }))
@DeclareRoles(JBOSS_ADMIN_ROLE)
public class ComplexServletRemote extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
private ManagementBeanRemote bean;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
Writer writer = resp.getWriter();
try {
writer.write(bean.whoAmI() + "," + String.valueOf(bean.invokeEntryDoIHaveRole("user")) + "," + String.valueOf(bean.invokeEntryDoIHaveRole("Managers")));
} catch (Exception e) {
throw new ServletException("Unexpected Failure", e);
}
}
}
| 2,561
| 38.415385
| 164
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/deployment/OidcWithDeploymentConfigTest.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.deployment;
import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode;
import static org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.getRealmRepresentation;
import java.util.HashMap;
import java.util.Map;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.SimpleSecuredServlet;
import org.jboss.as.test.integration.security.common.servlets.SimpleServlet;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration;
import org.wildfly.test.integration.elytron.oidc.client.OidcBaseTest;
import io.restassured.RestAssured;
/**
* Tests for the OpenID Connect authentication mechanism.
*
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ OidcWithDeploymentConfigTest.KeycloakAndSystemPropertySetup.class })
public class OidcWithDeploymentConfigTest extends OidcBaseTest {
private static final String OIDC_PROVIDER_URL = "oidc.provider.url";
private static final String OIDC_JSON_WITH_PROVIDER_URL_FILE = "OidcWithProviderUrl.json";
private static final String OIDC_AUTH_SERVER_URL = "oidc.auth.server.url";
private static final String OIDC_JSON_WITH_AUTH_SERVER_URL_FILE = "OidcWithAuthServerUrl.json";
private static final String WRONG_OIDC_PROVIDER_URL = "wrong.oidc.provider.url";
private static final String OIDC_JSON_WITH_WRONG_PROVIDER_URL_FILE = "OidcWithWrongProviderUrl.json";
private static final String OIDC_JSON_WITH_WRONG_SECRET_FILE = "OidcWithWrongSecret.json";
private static final String MISSING_EXPRESSION_APP = "MissingExpressionOidcApp";
private static final String OIDC_JSON_WITH_MISSING_EXPRESSION_FILE = "OidcWithMissingExpression.json";
private static final String BEARER_ONLY_WITH_AUTH_SERVER_URL_FILE = "BearerOnlyWithAuthServerUrl.json";
private static final String BEARER_ONLY_WITH_PROVIDER_URL_FILE = "BearerOnlyWithProviderUrl.json";
private static final String BASIC_AUTH_WITH_PROVIDER_URL_FILE = "BasicAuthWithProviderUrl.json";
private static final String CORS_WITH_PROVIDER_URL_FILE = "CorsWithProviderUrl.json";
private static Map<String, KeycloakConfiguration.ClientAppType> APP_NAMES;
static {
APP_NAMES = new HashMap<>();
APP_NAMES.put(PROVIDER_URL_APP, KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
APP_NAMES.put(AUTH_SERVER_URL_APP, KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
APP_NAMES.put(WRONG_PROVIDER_URL_APP, KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
APP_NAMES.put(WRONG_SECRET_APP, KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
APP_NAMES.put(MISSING_EXPRESSION_APP, KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
APP_NAMES.put(DIRECT_ACCCESS_GRANT_ENABLED_CLIENT, KeycloakConfiguration.ClientAppType.DIRECT_ACCESS_GRANT_OIDC_CLIENT);
APP_NAMES.put(BEARER_ONLY_AUTH_SERVER_URL_APP, KeycloakConfiguration.ClientAppType.BEARER_ONLY_CLIENT);
APP_NAMES.put(BEARER_ONLY_PROVIDER_URL_APP, KeycloakConfiguration.ClientAppType.BEARER_ONLY_CLIENT);
APP_NAMES.put(BASIC_AUTH_PROVIDER_URL_APP, KeycloakConfiguration.ClientAppType.BEARER_ONLY_CLIENT);
APP_NAMES.put(CORS_PROVIDER_URL_APP, KeycloakConfiguration.ClientAppType.BEARER_ONLY_CLIENT);
APP_NAMES.put(CORS_CLIENT, KeycloakConfiguration.ClientAppType.CORS_CLIENT);
}
@ArquillianResource
protected static Deployer deployer;
@Deployment(name = PROVIDER_URL_APP, managed = false, testable = false)
public static WebArchive createProviderUrlDeployment() {
return ShrinkWrap.create(WebArchive.class, PROVIDER_URL_APP + ".war")
.addClasses(SimpleServlet.class)
.addClasses(SimpleSecuredServlet.class)
.addAsWebInfResource(OidcWithDeploymentConfigTest.class.getPackage(), OIDC_WITHOUT_SUBSYSTEM_CONFIG_WEB_XML, "web.xml")
.addAsWebInfResource(OidcWithDeploymentConfigTest.class.getPackage(), OIDC_JSON_WITH_PROVIDER_URL_FILE, "oidc.json");
}
@Deployment(name = AUTH_SERVER_URL_APP, managed = false, testable = false)
public static WebArchive createAuthServerUrlDeployment() {
return ShrinkWrap.create(WebArchive.class, AUTH_SERVER_URL_APP + ".war")
.addClasses(SimpleServlet.class)
.addClasses(SimpleSecuredServlet.class)
.addAsWebInfResource(OidcWithDeploymentConfigTest.class.getPackage(), OIDC_WITHOUT_SUBSYSTEM_CONFIG_WEB_XML, "web.xml")
.addAsWebInfResource(OidcWithDeploymentConfigTest.class.getPackage(), OIDC_JSON_WITH_AUTH_SERVER_URL_FILE, "oidc.json");
}
@Deployment(name = WRONG_PROVIDER_URL_APP, managed = false, testable = false)
public static WebArchive createWrongProviderUrlDeployment() {
return ShrinkWrap.create(WebArchive.class, WRONG_PROVIDER_URL_APP + ".war")
.addClasses(SimpleServlet.class)
.addClasses(SimpleSecuredServlet.class)
.addAsWebInfResource(OidcWithDeploymentConfigTest.class.getPackage(), OIDC_WITHOUT_SUBSYSTEM_CONFIG_WEB_XML, "web.xml")
.addAsWebInfResource(OidcWithDeploymentConfigTest.class.getPackage(), OIDC_JSON_WITH_WRONG_PROVIDER_URL_FILE, "oidc.json");
}
@Deployment(name = WRONG_SECRET_APP, managed = false, testable = false)
public static WebArchive createWrongSecretDeployment() {
return ShrinkWrap.create(WebArchive.class, WRONG_SECRET_APP + ".war")
.addClasses(SimpleServlet.class)
.addClasses(SimpleSecuredServlet.class)
.addAsWebInfResource(OidcWithDeploymentConfigTest.class.getPackage(), OIDC_WITHOUT_SUBSYSTEM_CONFIG_WEB_XML, "web.xml")
.addAsWebInfResource(OidcWithDeploymentConfigTest.class.getPackage(), OIDC_JSON_WITH_WRONG_SECRET_FILE, "oidc.json");
}
@Deployment(name = MISSING_EXPRESSION_APP, managed = false, testable = false)
public static WebArchive createMissingExpressionDeployment() {
return ShrinkWrap.create(WebArchive.class, MISSING_EXPRESSION_APP + ".war")
.addClasses(SimpleServlet.class)
.addClasses(SimpleSecuredServlet.class)
.addAsWebInfResource(OidcWithDeploymentConfigTest.class.getPackage(), OIDC_WITHOUT_SUBSYSTEM_CONFIG_WEB_XML, "web.xml")
.addAsWebInfResource(OidcWithDeploymentConfigTest.class.getPackage(), OIDC_JSON_WITH_MISSING_EXPRESSION_FILE, "oidc.json");
}
@Deployment(name = BEARER_ONLY_AUTH_SERVER_URL_APP, managed = false, testable = false)
public static WebArchive createBearerOnlyAuthServerUrlDeployment() {
return ShrinkWrap.create(WebArchive.class, BEARER_ONLY_AUTH_SERVER_URL_APP + ".war")
.addClasses(SimpleServlet.class)
.addClasses(SimpleSecuredServlet.class)
.addAsWebInfResource(OidcWithDeploymentConfigTest.class.getPackage(), OIDC_WITHOUT_SUBSYSTEM_CONFIG_WEB_XML, "web.xml")
.addAsWebInfResource(OidcWithDeploymentConfigTest.class.getPackage(), BEARER_ONLY_WITH_AUTH_SERVER_URL_FILE, "oidc.json");
}
@Deployment(name = BEARER_ONLY_PROVIDER_URL_APP, managed = false, testable = false)
public static WebArchive createBearerOnlyProviderUrlDeployment() {
return ShrinkWrap.create(WebArchive.class, BEARER_ONLY_PROVIDER_URL_APP + ".war")
.addClasses(SimpleServlet.class)
.addClasses(SimpleSecuredServlet.class)
.addAsWebInfResource(OidcWithDeploymentConfigTest.class.getPackage(), OIDC_WITHOUT_SUBSYSTEM_CONFIG_WEB_XML, "web.xml")
.addAsWebInfResource(OidcWithDeploymentConfigTest.class.getPackage(), BEARER_ONLY_WITH_PROVIDER_URL_FILE, "oidc.json");
}
@Deployment(name = BASIC_AUTH_PROVIDER_URL_APP, managed = false, testable = false)
public static WebArchive createBasicAuthProviderUrlDeployment() {
return ShrinkWrap.create(WebArchive.class, BASIC_AUTH_PROVIDER_URL_APP + ".war")
.addClasses(SimpleServlet.class)
.addClasses(SimpleSecuredServlet.class)
.addAsWebInfResource(OidcWithDeploymentConfigTest.class.getPackage(), OIDC_WITHOUT_SUBSYSTEM_CONFIG_WEB_XML, "web.xml")
.addAsWebInfResource(OidcWithDeploymentConfigTest.class.getPackage(), BASIC_AUTH_WITH_PROVIDER_URL_FILE, "oidc.json");
}
@Deployment(name = CORS_PROVIDER_URL_APP, managed = false, testable = false)
public static WebArchive createCorsProviderUrlDeployment() {
return ShrinkWrap.create(WebArchive.class, CORS_PROVIDER_URL_APP + ".war")
.addClasses(SimpleServlet.class)
.addClasses(SimpleSecuredServlet.class)
.addAsWebInfResource(OidcWithDeploymentConfigTest.class.getPackage(), OIDC_WITHOUT_SUBSYSTEM_CONFIG_WEB_XML, "web.xml")
.addAsWebInfResource(OidcWithDeploymentConfigTest.class.getPackage(), CORS_WITH_PROVIDER_URL_FILE, "oidc.json");
}
@Test
@InSequence(1)
public void testWrongPasswordWithProviderUrl() throws Exception {
deployer.deploy(PROVIDER_URL_APP);
super.testWrongPasswordWithProviderUrl();
}
@Test
@InSequence(2)
public void testSucessfulAuthenticationWithProviderUrl() throws Exception {
super.testSucessfulAuthenticationWithProviderUrl();
}
@Test
@InSequence(3)
public void testWrongRoleWithProviderUrl() throws Exception {
super.testWrongRoleWithProviderUrl();
}
@Test
@InSequence(4)
public void testTokenProvidedBearerOnlyNotSet() throws Exception {
super.testTokenProvidedBearerOnlyNotSet();
}
@Test
@InSequence(5)
public void testTokenNotProvidedBearerOnlyNotSet() throws Exception {
super.testTokenNotProvidedBearerOnlyNotSet();
}
@Test
@InSequence(6)
public void testBasicAuthenticationWithoutEnableBasicAuthSetAndWithoutBearerOnlySet() throws Exception {
try {
super.testBasicAuthenticationWithoutEnableBasicAuthSetAndWithoutBearerOnlySet();
} finally {
deployer.undeploy(PROVIDER_URL_APP);
}
}
@Test
@InSequence(7)
public void testWrongPasswordWithAuthServerUrl() throws Exception {
deployer.deploy(AUTH_SERVER_URL_APP);
super.testWrongPasswordWithAuthServerUrl();
}
@Test
@InSequence(8)
public void testSucessfulAuthenticationWithAuthServerUrl() throws Exception {
super.testSucessfulAuthenticationWithAuthServerUrl();
}
@Test
@InSequence(9)
public void testWrongRoleWithAuthServerUrl() throws Exception {
try {
super.testWrongRoleWithAuthServerUrl();
} finally {
deployer.undeploy(AUTH_SERVER_URL_APP);
}
}
@Test
public void testWrongProviderUrl() throws Exception {
try {
deployer.deploy(WRONG_PROVIDER_URL_APP);
super.testWrongProviderUrl();
} finally {
deployer.undeploy(WRONG_PROVIDER_URL_APP);
}
}
@Test
public void testWrongClientSecret() throws Exception {
try {
deployer.deploy(WRONG_SECRET_APP);
super.testWrongClientSecret();
} finally {
deployer.undeploy(WRONG_SECRET_APP);
}
}
@Test
public void testMissingExpression() throws Exception {
deployer.deploy(MISSING_EXPRESSION_APP);
try {
loginToApp(MISSING_EXPRESSION_APP, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD, -1, null, false);
} finally {
deployer.undeploy(MISSING_EXPRESSION_APP);
}
}
@Test
@InSequence(10)
public void testSucessfulBearerOnlyAuthenticationWithAuthServerUrl() throws Exception {
deployer.deploy(BEARER_ONLY_AUTH_SERVER_URL_APP);
super.testSucessfulBearerOnlyAuthenticationWithAuthServerUrl();
}
@Test
@InSequence(11)
public void testNoTokenProvidedWithAuthServerUrl() throws Exception {
try {
super.testNoTokenProvidedWithAuthServerUrl();
} finally {
deployer.undeploy(BEARER_ONLY_AUTH_SERVER_URL_APP);
}
}
@Test
@InSequence(12)
public void testSucessfulBearerOnlyAuthenticationWithProviderUrl() throws Exception {
deployer.deploy(BEARER_ONLY_PROVIDER_URL_APP);
super.testSucessfulBearerOnlyAuthenticationWithProviderUrl();
}
@Test
@InSequence(13)
public void testWrongToken() throws Exception {
super.testWrongToken();
}
@Test
@InSequence(14)
public void testInvalidToken() throws Exception {
super.testInvalidToken();
}
@Test
@InSequence(15)
public void testNoTokenProvidedWithProviderUrl() throws Exception {
super.testNoTokenProvidedWithProviderUrl();
}
@Test
@InSequence(16)
public void testValidTokenViaQueryParameter() throws Exception {
super.testValidTokenViaQueryParameter();
}
@Test
@InSequence(17)
public void testWrongTokenViaQueryParameter() throws Exception {
super.testWrongTokenViaQueryParameter();
}
@Test
@InSequence(18)
public void testInvalidTokenViaQueryParameter() throws Exception {
super.testInvalidTokenViaQueryParameter();
}
@Test
@InSequence(19)
public void testBasicAuthenticationWithoutEnableBasicAuthSet() throws Exception {
super.testBasicAuthenticationWithoutEnableBasicAuthSet();
}
@Test
@InSequence(20)
public void testCorsRequestWithoutEnableCors() throws Exception {
try {
super.testCorsRequestWithoutEnableCors();
} finally {
deployer.undeploy(BEARER_ONLY_PROVIDER_URL_APP);
}
}
@Test
@InSequence(21)
public void testValidCredentialsBasicAuthentication() throws Exception {
deployer.deploy(BASIC_AUTH_PROVIDER_URL_APP);
super.testValidCredentialsBasicAuthentication();
}
@Test
@InSequence(22)
public void testInvalidCredentialsBasicAuthentication() throws Exception {
try {
super.testInvalidCredentialsBasicAuthentication();
} finally {
deployer.undeploy(BASIC_AUTH_PROVIDER_URL_APP);
}
}
@Test
@InSequence(23)
public void testCorsRequestWithEnableCors() throws Exception {
deployer.deploy(CORS_PROVIDER_URL_APP);
super.testCorsRequestWithEnableCors();
}
@Test
@InSequence(24)
public void testCorsRequestWithEnableCorsWithWrongToken() throws Exception {
super.testCorsRequestWithEnableCorsWithWrongToken();
}
@Test
@InSequence(25)
public void testCorsRequestWithEnableCorsWithInvalidToken() throws Exception {
super.testCorsRequestWithEnableCorsWithInvalidToken();
}
@Test
@InSequence(26)
public void testCorsRequestWithEnableCorsWithInvalidOrigin() throws Exception {
try {
super.testCorsRequestWithEnableCorsWithInvalidOrigin();
} finally {
deployer.undeploy(CORS_PROVIDER_URL_APP);
}
}
static class KeycloakAndSystemPropertySetup extends KeycloakSetup {
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
super.setup(managementClient, containerId);
sendRealmCreationRequest(getRealmRepresentation(TEST_REALM, CLIENT_SECRET, CLIENT_HOST_NAME, CLIENT_PORT, APP_NAMES));
ModelControllerClient client = managementClient.getControllerClient();
ModelNode operation = createOpNode("system-property=" + OIDC_PROVIDER_URL, ModelDescriptionConstants.ADD);
operation.get("value").set(KEYCLOAK_CONTAINER.getAuthServerUrl() + "/realms/" + TEST_REALM);
Utils.applyUpdate(operation, client);
operation = createOpNode("system-property=" + OIDC_AUTH_SERVER_URL, ModelDescriptionConstants.ADD);
operation.get("value").set(KEYCLOAK_CONTAINER.getAuthServerUrl());
Utils.applyUpdate(operation, client);
operation = createOpNode("system-property=" + WRONG_OIDC_PROVIDER_URL, ModelDescriptionConstants.ADD);
operation.get("value").set("http://fakeauthserver/auth"); // provider url does not exist
Utils.applyUpdate(operation, client);
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
RestAssured
.given()
.auth().oauth2(org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.getAdminAccessToken(KEYCLOAK_CONTAINER.getAuthServerUrl()))
.when()
.delete(KEYCLOAK_CONTAINER.getAuthServerUrl() + "/admin/realms/" + TEST_REALM).then().statusCode(204);
super.tearDown(managementClient, containerId);
ModelControllerClient client = managementClient.getControllerClient();
ModelNode operation = createOpNode("system-property=" + OIDC_PROVIDER_URL, ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, client);
operation = createOpNode("system-property=" + OIDC_AUTH_SERVER_URL, ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, client);
operation = createOpNode("system-property=" + WRONG_OIDC_PROVIDER_URL, ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, client);
}
}
}
| 19,497
| 43.013544
| 165
|
java
|
null |
wildfly-main/testsuite/integration/elytron-oidc-client/src/test/java/org/wildfly/test/integration/elytron/oidc/client/subsystem/OidcWithSubsystemConfigTest.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.oidc.client.subsystem;
import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode;
import static org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration.getRealmRepresentation;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.SimpleSecuredServlet;
import org.jboss.as.test.integration.security.common.servlets.SimpleServlet;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.extension.elytron.oidc.ElytronOidcExtension;
import org.wildfly.test.integration.elytron.oidc.client.KeycloakConfiguration;
import org.wildfly.test.integration.elytron.oidc.client.OidcBaseTest;
import io.restassured.RestAssured;
/**
* Tests for the OpenID Connect authentication mechanism.
*
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ OidcWithSubsystemConfigTest.KeycloakAndSubsystemSetup.class })
public class OidcWithSubsystemConfigTest extends OidcBaseTest {
private static final String SUBSYSTEM_OVERRIDE_APP = "SubsystemOverrideOidcApp";
private static final String OIDC_JSON_WITH_SUBSYSTEM_OVERRIDE_FILE = "OidcWithSubsystemOverride.json";
private static final String KEYCLOAK_PROVIDER = "keycloak";
private static Map<String, KeycloakConfiguration.ClientAppType> APP_NAMES;
private static final String SECURE_DEPLOYMENT_ADDRESS = "subsystem=" + ElytronOidcExtension.SUBSYSTEM_NAME + "/secure-deployment=";
private static final String PROVIDER_ADDRESS = "subsystem=" + ElytronOidcExtension.SUBSYSTEM_NAME + "/provider=";
private static final String REALM_ADDRESS = "subsystem=" + ElytronOidcExtension.SUBSYSTEM_NAME + "/realm=";
static {
APP_NAMES = new HashMap<>();
APP_NAMES.put(PROVIDER_URL_APP, KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
APP_NAMES.put(AUTH_SERVER_URL_APP, KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
APP_NAMES.put(WRONG_PROVIDER_URL_APP, KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
APP_NAMES.put(WRONG_SECRET_APP, KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
APP_NAMES.put(SUBSYSTEM_OVERRIDE_APP, KeycloakConfiguration.ClientAppType.OIDC_CLIENT);
APP_NAMES.put(DIRECT_ACCCESS_GRANT_ENABLED_CLIENT, KeycloakConfiguration.ClientAppType.DIRECT_ACCESS_GRANT_OIDC_CLIENT);
APP_NAMES.put(BEARER_ONLY_AUTH_SERVER_URL_APP, KeycloakConfiguration.ClientAppType.BEARER_ONLY_CLIENT);
APP_NAMES.put(BEARER_ONLY_PROVIDER_URL_APP, KeycloakConfiguration.ClientAppType.BEARER_ONLY_CLIENT);
APP_NAMES.put(BASIC_AUTH_PROVIDER_URL_APP, KeycloakConfiguration.ClientAppType.BEARER_ONLY_CLIENT);
APP_NAMES.put(CORS_PROVIDER_URL_APP, KeycloakConfiguration.ClientAppType.BEARER_ONLY_CLIENT);
APP_NAMES.put(CORS_CLIENT, KeycloakConfiguration.ClientAppType.CORS_CLIENT);
}
@Deployment(name = PROVIDER_URL_APP)
public static WebArchive createProviderUrlDeployment() {
return ShrinkWrap.create(WebArchive.class, PROVIDER_URL_APP + ".war")
.addClasses(SimpleServlet.class)
.addClasses(SimpleSecuredServlet.class);
}
@Deployment(name = AUTH_SERVER_URL_APP)
public static WebArchive createAuthServerUrlDeployment() {
return ShrinkWrap.create(WebArchive.class, AUTH_SERVER_URL_APP + ".war")
.addClasses(SimpleServlet.class)
.addClasses(SimpleSecuredServlet.class);
}
@Deployment(name = WRONG_PROVIDER_URL_APP)
public static WebArchive createWrongProviderUrlDeployment() {
return ShrinkWrap.create(WebArchive.class, WRONG_PROVIDER_URL_APP + ".war")
.addClasses(SimpleServlet.class)
.addClasses(SimpleSecuredServlet.class);
}
@Deployment(name = WRONG_SECRET_APP)
public static WebArchive createWrongSecretDeployment() {
return ShrinkWrap.create(WebArchive.class, WRONG_SECRET_APP + ".war")
.addClasses(SimpleServlet.class)
.addClasses(SimpleSecuredServlet.class);
}
@Deployment(name = SUBSYSTEM_OVERRIDE_APP)
public static WebArchive createSubsystemOverrideDeployment() {
return ShrinkWrap.create(WebArchive.class, SUBSYSTEM_OVERRIDE_APP + ".war")
.addClasses(SimpleServlet.class)
.addClasses(SimpleSecuredServlet.class)
.addAsWebInfResource(OidcWithSubsystemConfigTest.class.getPackage(), OIDC_JSON_WITH_SUBSYSTEM_OVERRIDE_FILE, "oidc.json"); // has bad provider url
}
@Deployment(name = BEARER_ONLY_AUTH_SERVER_URL_APP)
public static WebArchive createBearerOnlyAuthServerUrlDeployment() {
return ShrinkWrap.create(WebArchive.class, BEARER_ONLY_AUTH_SERVER_URL_APP + ".war")
.addClasses(SimpleServlet.class)
.addClasses(SimpleSecuredServlet.class);
}
@Deployment(name = BEARER_ONLY_PROVIDER_URL_APP)
public static WebArchive createBearerOnlyProviderUrlDeployment() {
return ShrinkWrap.create(WebArchive.class, BEARER_ONLY_PROVIDER_URL_APP + ".war")
.addClasses(SimpleServlet.class)
.addClasses(SimpleSecuredServlet.class);
}
@Deployment(name = BASIC_AUTH_PROVIDER_URL_APP)
public static WebArchive createBasicAuthProviderUrlDeployment() {
return ShrinkWrap.create(WebArchive.class, BASIC_AUTH_PROVIDER_URL_APP + ".war")
.addClasses(SimpleServlet.class)
.addClasses(SimpleSecuredServlet.class);
}
@Deployment(name = CORS_PROVIDER_URL_APP)
public static WebArchive createCorsProviderUrlDeployment() {
return ShrinkWrap.create(WebArchive.class, CORS_PROVIDER_URL_APP + ".war")
.addClasses(SimpleServlet.class)
.addClasses(SimpleSecuredServlet.class);
}
@Test
@OperateOnDeployment(SUBSYSTEM_OVERRIDE_APP)
public void testSubsystemOverride() throws Exception {
// deployment contains an invalid provider-url but the subsystem contains a valid one, the subsystem config should take precedence
loginToApp(SUBSYSTEM_OVERRIDE_APP, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD, HttpURLConnection.HTTP_OK, SimpleServlet.RESPONSE_BODY);
}
static class KeycloakAndSubsystemSetup extends KeycloakSetup {
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
super.setup(managementClient, containerId);
sendRealmCreationRequest(getRealmRepresentation(TEST_REALM, CLIENT_SECRET, CLIENT_HOST_NAME, CLIENT_PORT, APP_NAMES));
ModelControllerClient client = managementClient.getControllerClient();
ModelNode operation = createOpNode(PROVIDER_ADDRESS + KEYCLOAK_PROVIDER , ModelDescriptionConstants.ADD);
operation.get("provider-url").set(KEYCLOAK_CONTAINER.getAuthServerUrl() + "/realms/" + TEST_REALM);
Utils.applyUpdate(operation, client);
operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + PROVIDER_URL_APP + ".war", ModelDescriptionConstants.ADD);
operation.get("client-id").set(PROVIDER_URL_APP);
operation.get("public-client").set(false);
operation.get("provider").set(KEYCLOAK_PROVIDER);
operation.get("ssl-required").set("EXTERNAL");
Utils.applyUpdate(operation, client);
operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + PROVIDER_URL_APP + ".war/credential=secret", ModelDescriptionConstants.ADD);
operation.get("secret").set("secret");
Utils.applyUpdate(operation, client);
operation = createOpNode(REALM_ADDRESS + TEST_REALM , ModelDescriptionConstants.ADD);
operation.get("auth-server-url").set(KEYCLOAK_CONTAINER.getAuthServerUrl());
Utils.applyUpdate(operation, client);
operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + AUTH_SERVER_URL_APP + ".war", ModelDescriptionConstants.ADD);
operation.get("resource").set(AUTH_SERVER_URL_APP);
operation.get("public-client").set(false);
operation.get("realm").set(TEST_REALM);
operation.get("ssl-required").set("EXTERNAL");
Utils.applyUpdate(operation, client);
operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + AUTH_SERVER_URL_APP + ".war/credential=secret", ModelDescriptionConstants.ADD);
operation.get("secret").set("secret");
Utils.applyUpdate(operation, client);
operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + WRONG_PROVIDER_URL_APP + ".war", ModelDescriptionConstants.ADD);
operation.get("client-id").set(WRONG_PROVIDER_URL_APP);
operation.get("public-client").set(false);
operation.get("provider-url").set("http://fakeauthserver/auth");
operation.get("ssl-required").set("EXTERNAL");
Utils.applyUpdate(operation, client);
operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + WRONG_PROVIDER_URL_APP + ".war/credential=secret", ModelDescriptionConstants.ADD);
operation.get("secret").set("secret");
Utils.applyUpdate(operation, client);
operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + WRONG_SECRET_APP + ".war", ModelDescriptionConstants.ADD);
operation.get("client-id").set(WRONG_SECRET_APP);
operation.get("public-client").set(false);
operation.get("provider-url").set(KEYCLOAK_CONTAINER.getAuthServerUrl() + "/realms/" + TEST_REALM);
operation.get("ssl-required").set("EXTERNAL");
Utils.applyUpdate(operation, client);
operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + WRONG_SECRET_APP + ".war/credential=secret", ModelDescriptionConstants.ADD);
operation.get("secret").set("WRONG_SECRET");
Utils.applyUpdate(operation, client);
operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + SUBSYSTEM_OVERRIDE_APP + ".war", ModelDescriptionConstants.ADD);
operation.get("client-id").set(SUBSYSTEM_OVERRIDE_APP);
operation.get("public-client").set(false);
operation.get("provider").set(KEYCLOAK_PROVIDER);
operation.get("ssl-required").set("EXTERNAL");
Utils.applyUpdate(operation, client);
operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + SUBSYSTEM_OVERRIDE_APP + ".war/credential=secret", ModelDescriptionConstants.ADD);
operation.get("secret").set("secret");
Utils.applyUpdate(operation, client);
operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + BEARER_ONLY_AUTH_SERVER_URL_APP + ".war", ModelDescriptionConstants.ADD);
operation.get("resource").set(BEARER_ONLY_AUTH_SERVER_URL_APP);
operation.get("public-client").set(false);
operation.get("realm").set(TEST_REALM);
operation.get("ssl-required").set("EXTERNAL");
operation.get("bearer-only").set("true");
Utils.applyUpdate(operation, client);
operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + BEARER_ONLY_PROVIDER_URL_APP + ".war", ModelDescriptionConstants.ADD);
operation.get("client-id").set(BEARER_ONLY_PROVIDER_URL_APP);
operation.get("public-client").set(false);
operation.get("provider").set(KEYCLOAK_PROVIDER);
operation.get("ssl-required").set("EXTERNAL");
operation.get("bearer-only").set("true");
Utils.applyUpdate(operation, client);
operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + BASIC_AUTH_PROVIDER_URL_APP + ".war", ModelDescriptionConstants.ADD);
operation.get("client-id").set(DIRECT_ACCCESS_GRANT_ENABLED_CLIENT);
operation.get("public-client").set(false);
operation.get("provider").set(KEYCLOAK_PROVIDER);
operation.get("ssl-required").set("EXTERNAL");
operation.get("enable-basic-auth").set("true");
Utils.applyUpdate(operation, client);
operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + BASIC_AUTH_PROVIDER_URL_APP + ".war/credential=secret", ModelDescriptionConstants.ADD);
operation.get("secret").set("secret");
Utils.applyUpdate(operation, client);
operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + CORS_PROVIDER_URL_APP + ".war", ModelDescriptionConstants.ADD);
operation.get("client-id").set(CORS_PROVIDER_URL_APP);
operation.get("public-client").set(false);
operation.get("provider").set(KEYCLOAK_PROVIDER);
operation.get("ssl-required").set("EXTERNAL");
operation.get("bearer-only").set("true");
operation.get("enable-cors").set("true");
Utils.applyUpdate(operation, client);
ServerReload.executeReloadAndWaitForCompletion(managementClient);
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
ModelControllerClient client = managementClient.getControllerClient();
for (String appName : APP_NAMES.keySet()) {
if (! appName.equals(CORS_CLIENT) && ! appName.equals(DIRECT_ACCCESS_GRANT_ENABLED_CLIENT)) {
removeSecureDeployment(client, appName);
}
}
removeProvider(client, KEYCLOAK_PROVIDER);
removeRealm(client, TEST_REALM);
RestAssured
.given()
.auth().oauth2(KeycloakConfiguration.getAdminAccessToken(KEYCLOAK_CONTAINER.getAuthServerUrl()))
.when()
.delete(KEYCLOAK_CONTAINER.getAuthServerUrl() + "/admin/realms/" + TEST_REALM).then().statusCode(204);
super.tearDown(managementClient, containerId);
}
private static void removeSecureDeployment(ModelControllerClient client, String name) throws Exception {
ModelNode operation = createOpNode(SECURE_DEPLOYMENT_ADDRESS + name + ".war", ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, client);
}
private static void removeProvider(ModelControllerClient client, String provider) throws Exception {
ModelNode operation = createOpNode(PROVIDER_ADDRESS + provider, ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, client);
}
private static void removeRealm(ModelControllerClient client, String realm) throws Exception {
ModelNode operation = createOpNode(REALM_ADDRESS + realm, ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, client);
}
}
}
| 16,649
| 53.411765
| 166
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/smoke/web/SimpleLegacyServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.smoke.web;
import java.io.IOException;
import java.io.Writer;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
*
* @author <a href="kabir.khan@jboss.com">Kabir Khan</a>
* @version $Revision: 1.1 $
*/
public class SimpleLegacyServlet extends HttpServlet {
private static final long serialVersionUID = -2579304186167063651L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String msg = req.getParameter("input");
Writer writer = resp.getWriter();
writer.write("Simple Legacy Servlet called with input=" + msg);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doGet(req, resp);
}
}
| 2,009
| 34.892857
| 75
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/smoke/web/WarTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.smoke.web;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
*
* @author <a href="kabir.khan@jboss.com">Kabir Khan</a>
* @version $Revision: 1.1 $
*/
@RunWith(Arquillian.class)
@RunAsClient
public class WarTestCase {
@ArquillianResource
private URL url;
@Deployment(testable = false)
public static Archive<?> getDeployment() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, "war-example.war");
war.addPackage(WarTestCase.class.getPackage());
war.setWebXML(WarTestCase.class.getPackage(), "web.xml");
return war;
}
@Test
public void testServlet() throws Exception {
String s = performCall("simple", "Hello");
Assert.assertEquals("Simple Servlet called with input=Hello", s);
}
@Test
public void testLegacyServlet() throws Exception {
String s = performCall("legacy", "Hello");
Assert.assertEquals("Simple Legacy Servlet called with input=Hello", s);
}
private String performCall(String urlPattern, String param) throws Exception {
URL url = new URL(this.url.toExternalForm() + urlPattern + "?input=" + param);
return HttpRequest.get(url.toExternalForm(), 10, TimeUnit.SECONDS);
}
}
| 2,793
| 35.763158
| 86
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/smoke/web/WarNotAsClientTest.java
|
/*
* #%L
* Gravia :: Integration Tests :: Common
* %%
* Copyright (C) 2010 - 2013 JBoss by Red Hat
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
package org.jboss.as.test.smoke.web;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test WAR not as client.
*
* @author thomas.diesler@jboss.com
* @since 01-Oct-2013
*/
@RunWith(Arquillian.class)
public class WarNotAsClientTest {
@Deployment
public static Archive<?> deployment() {
return ShrinkWrap.create(WebArchive.class, "simple.war");
}
@Test
public void testWarDeployed() throws Exception {
Assert.assertTrue(true);
}
}
| 1,559
| 29
| 71
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/smoke/web/SimpleServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.smoke.web;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
/**
*
* @author <a href="kabir.khan@jboss.com">Kabir Khan</a>
* @version $Revision: 1.1 $
*/
@WebServlet(name="SimpleServlet", urlPatterns={"/simple"})
public class SimpleServlet extends HttpServlet {
private static final long serialVersionUID = -2579304186167063651L;
private volatile String message;
@PostConstruct
public void messageSetup() {
message = "Simple Servlet called with input=";
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String msg = req.getParameter("input");
Writer writer = resp.getWriter();
writer.write(message + msg);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doGet(req, resp);
}
}
| 2,265
| 33.861538
| 75
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/deployment/classloading/war/WarClassLoadingTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.deployment.classloading.war;
import static org.junit.Assert.*;
import java.net.URL;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.jboss.as.test.integration.common.WebInfLibClass;
@RunWith(Arquillian.class)
public class WarClassLoadingTestCase {
@Deployment
public static Archive<?> deploy() {
WebArchive war = ShrinkWrap.create(WebArchive.class);
war.addClass(WarClassLoadingTestCase.class);
war.add(EmptyAsset.INSTANCE, "META-INF/example.txt");
war.add(EmptyAsset.INSTANCE, "example2.txt");
JavaArchive libJar = ShrinkWrap.create(JavaArchive.class);
libJar.addClass(WebInfLibClass.class);
war.addAsLibraries(libJar);
return war;
}
@Test
public void testWebInfLibAccessible() throws ClassNotFoundException {
loadClass("org.jboss.as.test.integration.common.WebInfLibClass");
}
/*
* Test case for AS7-5172. Ensure META-INF/* is accessible
*/
@Test
public void testMetaInfAccessible() throws ClassNotFoundException {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
URL manifestResource = cl.getResource("META-INF/example.txt");
assertNotNull(manifestResource);
}
/*
* Test case for AS7-5172. Ensure that non-META-INF/* is not accessible
*/
@Test
public void testNonMetaInfNotAccessible() throws ClassNotFoundException {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
URL nonManifestResource = cl.getResource("example2.txt");
assertNull(nonManifestResource);
}
private static Class<?> loadClass(String name) throws ClassNotFoundException {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl != null) {
try {
return Class.forName(name, false, cl);
} catch (ClassNotFoundException ex) {
return Class.forName(name);
}
} else
return Class.forName(name);
}
}
| 3,438
| 36.380435
| 82
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/deployment/deploymentoverlay/DeploymentOverlayTestCase.java
|
package org.jboss.as.test.integration.deployment.deploymentoverlay;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.client.OperationBuilder;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.integration.management.ManagementOperations;
import org.jboss.as.test.integration.management.util.MgmtOperationException;
import org.jboss.as.test.shared.FileUtils;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
@ServerSetup(DeploymentOverlayTestCase.DeploymentOverlayTestCaseServerSetup.class)
public class DeploymentOverlayTestCase {
public static final String TEST_OVERLAY = "test";
public static final String TEST_WILDCARD = "test-wildcard";
static class DeploymentOverlayTestCaseServerSetup implements ServerSetupTask {
@Override
public void setup(final ManagementClient managementClient, final String containerId) throws Exception {
ModelNode op = new ModelNode();
op.get(ModelDescriptionConstants.OP_ADDR).set(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_OVERLAY);
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
//add an override that will not be linked via a wildcard
op = new ModelNode();
op.get(ModelDescriptionConstants.OP_ADDR).set(new ModelNode());
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.UPLOAD_DEPLOYMENT_BYTES);
op.get(ModelDescriptionConstants.BYTES).set(FileUtils.readFile(DeploymentOverlayTestCase.class, "override.xml").getBytes(StandardCharsets.UTF_8));
ModelNode result = ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
//add the content
op = new ModelNode();
ModelNode addr = new ModelNode();
addr.add(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_OVERLAY);
addr.add(ModelDescriptionConstants.CONTENT, "WEB-INF/web.xml");
op.get(ModelDescriptionConstants.OP_ADDR).set(addr);
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD);
op.get(ModelDescriptionConstants.CONTENT).get(ModelDescriptionConstants.HASH).set(result);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
//add the non-wildcard link
op = new ModelNode();
addr = new ModelNode();
addr.add(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_OVERLAY);
addr.add(ModelDescriptionConstants.DEPLOYMENT, "test.war");
op.get(ModelDescriptionConstants.OP_ADDR).set(addr);
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
//add the deployment overlay that will be linked via wildcard
op = new ModelNode();
op.get(ModelDescriptionConstants.OP_ADDR).set(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_WILDCARD);
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
op = new ModelNode();
addr = new ModelNode();
addr.add(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_WILDCARD);
addr.add(ModelDescriptionConstants.CONTENT, "WEB-INF/web.xml");
op.get(ModelDescriptionConstants.OP_ADDR).set(addr);
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD);
op.get(ModelDescriptionConstants.CONTENT).get(ModelDescriptionConstants.BYTES)
.set(FileUtils.readFile(DeploymentOverlayTestCase.class, "wildcard-override.xml").getBytes(StandardCharsets.UTF_8));
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
op = new ModelNode();
addr = new ModelNode();
addr.add(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_WILDCARD);
addr.add(ModelDescriptionConstants.CONTENT, "WEB-INF/classes/wildcard-new-file");
op.get(ModelDescriptionConstants.OP_ADDR).set(addr);
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD);
op.get(ModelDescriptionConstants.CONTENT).get(ModelDescriptionConstants.INPUT_STREAM_INDEX).set(0);
OperationBuilder builder = new OperationBuilder(op, true);
builder.addInputStream(DeploymentOverlayTestCase.class.getResourceAsStream("wildcard-new-file"));
ManagementOperations.executeOperation(managementClient.getControllerClient(), builder.build());
//add the wildcard link
op = new ModelNode();
addr = new ModelNode();
addr.add(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_WILDCARD);
addr.add(ModelDescriptionConstants.DEPLOYMENT, "*.war");
op.get(ModelDescriptionConstants.OP_ADDR).set(addr);
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
}
@Override
public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception {
removeContentItem(managementClient, TEST_OVERLAY, "WEB-INF/web.xml");
removeDeploymentItem(managementClient, TEST_OVERLAY, "test.war");
ModelNode op = new ModelNode();
op.get(ModelDescriptionConstants.OP_ADDR).set(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_OVERLAY);
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.REMOVE);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
removeDeploymentItem(managementClient, TEST_WILDCARD, "*.war");
removeContentItem(managementClient, TEST_WILDCARD, "WEB-INF/web.xml");
removeContentItem(managementClient, TEST_WILDCARD, "WEB-INF/classes/wildcard-new-file");
op = new ModelNode();
op.get(ModelDescriptionConstants.OP_ADDR).set(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_WILDCARD);
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.REMOVE);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
}
private void removeContentItem(final ManagementClient managementClient, final String w, final String a) throws IOException, MgmtOperationException {
final ModelNode op;
final ModelNode addr;
op = new ModelNode();
addr = new ModelNode();
addr.add(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, w);
addr.add(ModelDescriptionConstants.CONTENT, a);
op.get(ModelDescriptionConstants.OP_ADDR).set(addr);
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.REMOVE);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
}
private void removeDeploymentItem(final ManagementClient managementClient, final String w, final String a) throws IOException, MgmtOperationException {
final ModelNode op;
final ModelNode addr;
op = new ModelNode();
addr = new ModelNode();
addr.add(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, w);
addr.add(ModelDescriptionConstants.DEPLOYMENT, a);
op.get(ModelDescriptionConstants.OP_ADDR).set(addr);
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.REMOVE);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
}
}
@Deployment
public static Archive<?> deploy() {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addPackage(DeploymentOverlayTestCase.class.getPackage())
.setWebXML(DeploymentOverlayTestCase.class.getPackage(), "web.xml");
}
@ArquillianResource
private InitialContext initialContext;
@Test
public void testContentOverridden() throws NamingException {
Assert.assertEquals("OVERRIDDEN", initialContext.lookup("java:module/env/simpleString"));
}
@Test
public void testAddingNewFile() {
Assert.assertNotNull(getClass().getClassLoader().getResource("wildcard-new-file"));
}
}
| 9,389
| 49.483871
| 159
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/deployment/resourcelisting/WarResourceListingTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.deployment.resourcelisting;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.integration.common.WebInfLibClass;
import org.jboss.as.test.shared.ResourceListingUtils;
import org.jboss.logging.Logger;
import org.jboss.modules.ModuleClassLoader;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@RunWith(Arquillian.class)
public class WarResourceListingTestCase {
private static final Logger log = Logger.getLogger(WarResourceListingTestCase.class);
private static final String jarLibName = "innerJarLibrary.jar";
/**
* @return war archive with different types of web.xml
*/
@Deployment
public static Archive<?> deploy() {
WebArchive war = ShrinkWrap.create(WebArchive.class);
war.addClass(WarResourceListingTestCase.class);
war.addClass(ResourceListingUtils.class);
war.add(EmptyAsset.INSTANCE, "META-INF/properties/nested.properties");
war.add(EmptyAsset.INSTANCE, "META-INF/example.txt");
war.add(EmptyAsset.INSTANCE, "example2.txt");
war.addAsResource(WarResourceListingTestCase.class.getPackage(), "TextFile1.txt", "TextFile1.txt");
war.addAsWebInfResource(WarResourceListingTestCase.class.getPackage(), "web.xml", "web.xml");
JavaArchive libJar = ShrinkWrap.create(JavaArchive.class, jarLibName);
libJar.addClass(WebInfLibClass.class);
war.addAsLibraries(libJar);
return war;
}
@Test()
public void testRecursiveResourceRetrieval() {
log.trace("Test recursive listing of resources");
doTestResourceRetrieval(true, "/");
}
@Test()
public void testNonRecursiveResourceRetrieval() {
log.trace("Test nonrecursive listing of resources");
doTestResourceRetrieval(false, "/");
}
@Test()
public void testRecursiveResourceRetrievalForSpecifiedRootDir() {
log.trace("Test recursive listing of resources in specific directory");
doTestResourceRetrieval(true, "/WEB-INF");
}
@Test()
public void testNonRecursiveResourceRetrievalForSpecifiedRootDir() {
log.trace("Test recursive listing of resources in specific directory");
doTestResourceRetrieval(false, "/WEB-INF");
}
@Test()
public void testDirectResourceRetrieval() {
log.trace("Test accessing resources using getResource method");
ModuleClassLoader classLoader = (ModuleClassLoader) getClass().getClassLoader();
// checking that resource under META-INF is accessible
URL manifestResource = classLoader.getResource("META-INF/example.txt");
assertNotNull("Resource in META-INF should be accessible", manifestResource);
// checking that resource under META-INF is accessible
URL nestedManifestResource = classLoader.getResource("META-INF/properties/nested.properties");
assertNotNull("Nested resource should be also accessible", nestedManifestResource);
// checking that resource which is not under META-INF is not accessible
URL nonManifestResource = classLoader.getResource("example2.txt");
assertNull("Resource in the root of WAR shouldn't be accessible", nonManifestResource);
}
/**
* Based on provided parameters it filters which resources should be available and which not and tests if the retrieved resources matches this list
* @param recursive also a nested/recursive resources are counted
* @param rootDir represents the filtering by root directory (only resources in the specified root dir are taken into account
*/
private void doTestResourceRetrieval(boolean recursive, String rootDir) {
ModuleClassLoader classLoader = (ModuleClassLoader) getClass().getClassLoader();
List<String> resourcesInDeployment = getActualResourcesInWar(recursive, rootDir);
List<String> foundResources = ResourceListingUtils.listResources(classLoader, rootDir, recursive);
Collections.sort(foundResources);
log.trace("List of expected resources:");
for (String expectedResource : resourcesInDeployment) {
log.trace(expectedResource);
}
log.trace("List of found resources: ");
for (String foundResource : foundResources) {
log.trace(foundResource);
}
Assert.assertArrayEquals("Not all resources from WAR archive are correctly listed", resourcesInDeployment.toArray(), foundResources.toArray());
}
/**
* Returns all the resources in WAR archive
*
* @param recursive -- if even recursive resources (taken from rootDir) shall be provided
* @param rootDir -- can be used for getting resources only from specific rootDir
* @return list of resources in WAR filtered based on specified arguments
*/
public static List<String> getActualResourcesInWar(boolean recursive, String rootDir) {
String[] resourcesInWar = new String[]{
"META-INF/example.txt",
"META-INF/MANIFEST.MF",
"META-INF/properties/nested.properties",
"TextFile1.txt",
};
List<String> actualResources = new ArrayList<String>(Arrays.asList(resourcesInWar));
Class[] clazzes = new Class[] {
WarResourceListingTestCase.class,
ResourceListingUtils.class,
WebInfLibClass.class
};
for (Class clazz : clazzes) {
actualResources.add(ResourceListingUtils.classToPath(clazz));
}
ResourceListingUtils.filterResources(actualResources, rootDir, !recursive);
Collections.sort(actualResources);
return actualResources;
}
}
| 7,279
| 39.444444
| 151
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/annotationsmodule/WebModuleDeploymentTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.annotationsmodule;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.jandex.Index;
import org.jboss.jandex.IndexWriter;
import org.jboss.jandex.Indexer;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.ByteArrayAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import static org.junit.Assert.assertEquals;
/**
* Tests that servlets defined by annodations in a static module are picked up
*
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
@RunAsClient
public class WebModuleDeploymentTestCase {
public static void doSetup() throws Exception {
File testModuleRoot = new File(getModulePath(), "org/jboss/test/webModule");
File file = testModuleRoot;
while (!getModulePath().equals(file.getParentFile()))
file = file.getParentFile();
deleteRecursively(file);
createTestModule(testModuleRoot);
}
@AfterClass
public static void tearDown() throws Exception {
File testModuleRoot = new File(getModulePath(), "org/jboss/test/webModule");
File file = testModuleRoot;
while (!getModulePath().equals(file.getParentFile()))
file = file.getParentFile();
deleteRecursively(file);
}
private static void deleteRecursively(File file) {
if (file.exists()) {
if (file.isDirectory()) {
for (String name : file.list()) {
deleteRecursively(new File(file, name));
}
}
file.delete();
}
}
private static void createTestModule(File testModuleRoot) throws IOException {
if (testModuleRoot.exists()) {
throw new IllegalArgumentException(testModuleRoot + " already exists");
}
File file = new File(testModuleRoot, "main");
if (!file.mkdirs()) {
throw new IllegalArgumentException("Could not create " + file);
}
URL url = WebModuleDeploymentTestCase.class.getResource("module.xml");
if (url == null) {
throw new IllegalStateException("Could not find module.xml");
}
copyFile(new File(file, "module.xml"), url.openStream());
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "webTest.jar");
jar.addClasses(ModuleServlet.class);
Indexer indexer = new Indexer();
try (InputStream resource = ModuleServlet.class.getResourceAsStream(ModuleServlet.class.getSimpleName() + ".class")) {
indexer.index(resource);
}
Index index = indexer.complete();
ByteArrayOutputStream data = new ByteArrayOutputStream();
IndexWriter writer = new IndexWriter(data);
writer.write(index);
jar.addAsManifestResource(new ByteArrayAsset(data.toByteArray()), "jandex.idx");
FileOutputStream jarFile = new FileOutputStream(new File(file, "webTest.jar"));
try {
jar.as(ZipExporter.class).exportTo(jarFile);
} finally {
jarFile.flush();
jarFile.close();
}
}
private static void copyFile(File target, InputStream src) throws IOException {
Files.copy(src, target.toPath());
}
private static File getModulePath() {
String modulePath = System.getProperty("module.path", null);
if (modulePath == null) {
String jbossHome = System.getProperty("jboss.home", null);
if (jbossHome == null) {
throw new IllegalStateException("Neither -Dmodule.path nor -Djboss.home were set");
}
modulePath = jbossHome + File.separatorChar + "modules";
} else {
modulePath = modulePath.split(File.pathSeparator)[0];
}
File moduleDir = new File(modulePath);
if (!moduleDir.exists()) {
throw new IllegalStateException("Determined module path does not exist");
}
if (!moduleDir.isDirectory()) {
throw new IllegalStateException("Determined module path is not a dir");
}
return moduleDir;
}
@ArquillianResource
protected URL url;
@Deployment
public static Archive<?> deploy2() throws Exception {
doSetup();
WebArchive jar = ShrinkWrap.create(WebArchive.class, "webAnnotation.war");
jar.addClasses(WebModuleDeploymentTestCase.class);
jar.addAsManifestResource(new StringAsset("Dependencies: org.jboss.test.webModule meta-inf annotations\n"), "MANIFEST.MF");
return jar;
}
@Test
public void testSimpleBeanInjected() throws Exception {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpGet httpget = new HttpGet(url.toExternalForm() + "/servlet");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
assertEquals(200, statusLine.getStatusCode());
String result = EntityUtils.toString(entity);
Assert.assertEquals(ModuleServlet.MODULE_SERVLET, result);
}
}
}
| 7,188
| 36.836842
| 131
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/annotationsmodule/ModuleServlet.java
|
package org.jboss.as.test.integration.web.annotationsmodule;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author Stuart Douglas
*/
@WebServlet(name = "ModuleServlet", urlPatterns = "/servlet")
public class ModuleServlet extends HttpServlet {
public static final String MODULE_SERVLET = "Module Servlet";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write(MODULE_SERVLET);
}
}
| 713
| 30.043478
| 113
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/extension/SimpleUndertowExtension.java
|
package org.jboss.as.test.integration.web.extension;
import jakarta.servlet.ServletContext;
import io.undertow.io.IoCallback;
import io.undertow.server.HandlerWrapper;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.servlet.ServletExtension;
import io.undertow.servlet.api.DeploymentInfo;
/**
* @author Stuart Douglas
*/
public class SimpleUndertowExtension implements ServletExtension {
static final String THIS_IS_NOT_A_SERVLET = "This is not a servlet";
@Override
public void handleDeployment(final DeploymentInfo deploymentInfo, final ServletContext servletContext) {
deploymentInfo.addInitialHandlerChainWrapper(new HandlerWrapper() {
@Override
public HttpHandler wrap(final HttpHandler handler) {
return new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
if(Thread.currentThread() != exchange.getIoThread()) {
exchange.setStatusCode(500);
exchange.getResponseSender().send("Response was dispatched, not running in IO thread", IoCallback.END_EXCHANGE);
}
exchange.getResponseSender().send(THIS_IS_NOT_A_SERVLET, IoCallback.END_EXCHANGE);
}
};
}
});
}
}
| 1,468
| 37.657895
| 140
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/extension/UndertowNonBlockingHandlerTestCase.java
|
package org.jboss.as.test.integration.web.extension;
import java.net.URL;
import io.undertow.servlet.ServletExtension;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
/**
* Tests the use of Undertow extensions to register a non-blocking handler
*
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
@RunAsClient
public class UndertowNonBlockingHandlerTestCase {
@Deployment
public static WebArchive deploy() {
return ShrinkWrap.create(WebArchive.class, "non-blocking-handler.war")
.addPackage(UndertowNonBlockingHandlerTestCase.class.getPackage())
.addAsServiceProvider(ServletExtension.class, SimpleUndertowExtension.class);
}
@ArquillianResource
protected URL url;
@Test
public void testNonBlockingHandler() throws Exception {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpget = new HttpGet(url.toExternalForm());
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
assertEquals(200, statusLine.getStatusCode());
String result = EntityUtils.toString(entity);
Assert.assertEquals(SimpleUndertowExtension.THIS_IS_NOT_A_SERVLET, result);
}
}
}
| 2,052
| 33.216667
| 93
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/SecuredServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security;
import java.io.IOException;
import java.io.Writer;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HttpConstraint;
import jakarta.servlet.annotation.ServletSecurity;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* A simple servlet that just writes back a string
*
* @author Anil Saldhana
*/
@WebServlet(name = "SecuredServlet", urlPatterns = {"/secured/"}, loadOnStartup = 1)
@ServletSecurity(@HttpConstraint(rolesAllowed = {"gooduser"}))
public class SecuredServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Writer writer = resp.getWriter();
writer.write("GOOD\n");
writer.write("Remote user: " + req.getRemoteUser() + "\n");
writer.write("User principal: " + req.getUserPrincipal() + "\n");
writer.write("Authentication type: " + req.getAuthType());
}
}
| 2,218
| 39.345455
| 113
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/WebTestsSecurityDomainSetup.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security;
import java.io.File;
import java.net.URL;
import org.apache.commons.io.FileUtils;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.integration.management.util.CLIWrapper;
import org.jboss.as.test.integration.security.common.AbstractSecurityDomainSetup;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.logging.Logger;
import org.wildfly.test.security.common.elytron.PropertyFileBasedDomain;
import org.wildfly.test.security.common.elytron.UndertowDomainMapper;
/**
* @author Stuart Douglas
*/
public class WebTestsSecurityDomainSetup extends AbstractSecurityDomainSetup {
private static final Logger log = Logger.getLogger(WebTestsSecurityDomainSetup.class);
public static final String WEB_SECURITY_DOMAIN = "web-tests";
private static final String GOOD_USER_NAME = "anil";
private static final String GOOD_USER_PASSWORD = "anil";
private static final String GOOD_USER_ROLE = "gooduser";
private static final String SUPER_USER_NAME = "marcus";
private static final String SUPER_USER_PASSWORD = "marcus";
private static final String SUPER_USER_ROLE = "superuser";
private static final String BAD_GUY_NAME = "peter";
private static final String BAD_GUY_PASSWORD = "peter";
private static final String BAD_GUY_ROLE = "badguy";
private CLIWrapper cli;
private PropertyFileBasedDomain ps;
private UndertowDomainMapper domainMapper;
@Override
public void setup(final ManagementClient managementClient, final String containerId) throws Exception {
// Retrieve application.keystore file from jar archive of wildfly-testsuite-shared module
File destFile = new File(System.getProperty("jboss.home") + File.separator + "standalone" + File.separator +
"configuration" + File.separatorChar + "application.keystore");
URL resourceUrl = this.getClass().getResource("/org/jboss/as/test/shared/shared-keystores/application.keystore");
FileUtils.copyInputStreamToFile(resourceUrl.openStream(), destFile);
cli = new CLIWrapper(true);
setElytronBased();
}
@Override
protected String getSecurityDomainName() {
return WEB_SECURITY_DOMAIN;
}
protected void setElytronBased() throws Exception {
log.debug("start of the elytron based domain creation");
// Prepare properties files with users, passwords and roles
ps = PropertyFileBasedDomain.builder()
.withUser(GOOD_USER_NAME, GOOD_USER_PASSWORD, GOOD_USER_ROLE)
.withUser(SUPER_USER_NAME, SUPER_USER_PASSWORD, SUPER_USER_ROLE)
.withUser(BAD_GUY_NAME, BAD_GUY_PASSWORD, BAD_GUY_ROLE)
.withName(WEB_SECURITY_DOMAIN).build();
ps.create(cli);
domainMapper = UndertowDomainMapper.builder().withName(WEB_SECURITY_DOMAIN).build();
domainMapper.create(cli);
log.debug("end of the elytron based domain creation");
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) {
try {
domainMapper.remove(cli);
ps.remove(cli);
cli.close();
ServerReload.executeReloadAndWaitForCompletion(managementClient);
} catch (Exception e) {
throw new RuntimeException("Cleaning up for Elytron based security domain failed.", e);
}
}
}
| 4,487
| 42.153846
| 121
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/servlet3/RoleNamesAnnotationsServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.servlet3;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HttpConstraint;
import jakarta.servlet.annotation.ServletSecurity;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* A simple servlet that tries to do a programmatic login
*
* @author <a href="mailto:mmoyses@redhat.com">Marcus Moyses</a> TODO
*/
public class RoleNamesAnnotationsServlet {
/**
* A simple servlet that restricts access only to users registered among war security-roles.
*
* @author Jan Stourac
*/
@WebServlet(name = "RoleNamesAnnotationsSecuredServlet", urlPatterns = {ServletSecurityRoleNamesCommon
.SECURED_INDEX}, loadOnStartup = 1)
@ServletSecurity(@HttpConstraint(rolesAllowed = {"*"}))
public static class RoleNamesAnnotationsSecuredServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write(ServletSecurityRoleNamesCommon.SECURED_INDEX_CONTENT);
}
}
/**
* A simple servlet that restricts access only to any logged-in users.
*
* @author Jan Stourac
*/
@WebServlet(name = "RoleNamesAnnotationsWeaklySecuredServlet", urlPatterns = {ServletSecurityRoleNamesCommon
.WEAKLY_SECURED_INDEX}, loadOnStartup = 1)
@ServletSecurity(@HttpConstraint(rolesAllowed = {"**"}))
public static class RoleNamesAnnotationsWeaklySecuredServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write(ServletSecurityRoleNamesCommon.WEAKLY_SECURED_INDEX_CONTENT);
}
}
/**
* A simple servlet that restricts access to any users.
*
* @author Jan Stourac
*/
@WebServlet(name = "RoleNamesAnnotationsHardSecuredServlet", urlPatterns = {ServletSecurityRoleNamesCommon
.HARD_SECURED_INDEX}, loadOnStartup = 1)
@ServletSecurity(@HttpConstraint(value = ServletSecurity.EmptyRoleSemantic.DENY, rolesAllowed = {}))
public static class RoleNamesAnnotationsHardSecuredServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write(ServletSecurityRoleNamesCommon.HARD_SECURED_INDEX_CONTENT);
}
}
}
| 3,717
| 42.741176
| 117
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/servlet3/ServletSecurityRoleNamesTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.servlet3;
import java.net.URL;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.categories.CommonCriteria;
import org.jboss.as.test.integration.web.security.WebTestsSecurityDomainSetup;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
/**
* Unit Test the 'role-name' elements defined in the web.xml work as expected.
*
* @author Jan Stourac
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(WebTestsSecurityDomainSetup.class)
@Category(CommonCriteria.class)
public class ServletSecurityRoleNamesTestCase extends ServletSecurityRoleNamesCommon {
private static final String warName = ServletSecurityRoleNamesTestCase.class.getName();
@ArquillianResource
protected URL url;
@Deployment
public static WebArchive deployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, warName + WAR_SUFFIX);
war.addAsWebInfResource(ServletSecurityRoleNamesTestCase.class.getPackage(), "jboss-web.xml", "jboss-web" +
".xml");
war.setWebXML(ServletSecurityRoleNamesTestCase.class.getPackage(), "role-names-web.xml");
war.addAsWebResource(new StringAsset(SECURED_INDEX_CONTENT), "/" + SECURED_INDEX);
war.addAsWebResource(new StringAsset(WEAKLY_SECURED_INDEX_CONTENT), "/" + WEAKLY_SECURED_INDEX);
war.addAsWebResource(new StringAsset(HARD_SECURED_INDEX_CONTENT), "/" + HARD_SECURED_INDEX);
war.addPackage(CommonCriteria.class.getPackage());
return war;
}
protected void makeCallSecured(String user, String pass, int expectedCode) throws Exception {
makeCall(user, pass, expectedCode, new URL(url.toExternalForm() + SECURED_INDEX));
}
protected void makeCallWeaklySecured(String user, String pass, int expectedCode) throws Exception {
makeCall(user, pass, expectedCode, new URL(url.toExternalForm() + WEAKLY_SECURED_INDEX));
}
protected void makeCallHardSecured(String user, String pass, int expectedCode) throws Exception {
makeCall(user, pass, expectedCode, new URL(url.toExternalForm() + HARD_SECURED_INDEX));
}
}
| 3,580
| 43.7625
| 115
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/servlet3/ServletSecurityRoleNamesCommon.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.servlet3;
import static org.junit.Assert.assertEquals;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
/**
* Common part for testing servlet role-names.
*
* @author Jan Stourac
*/
public abstract class ServletSecurityRoleNamesCommon {
protected static final String WAR_SUFFIX = ".war";
protected static final String SECURED_INDEX = "secured/index.html";
protected static final String WEAKLY_SECURED_INDEX = "weakly-secured/index.html";
protected static final String HARD_SECURED_INDEX = "hard-secured/index.html";
protected static final String SECURED_INDEX_CONTENT = "GOOD - secured";
protected static final String WEAKLY_SECURED_INDEX_CONTENT = "GOOD weakly secured";
protected static final String HARD_SECURED_INDEX_CONTENT = "GOOD - hard secured";
/**
* Test with user "anil" who has the right password and the right role to access the servlet.
*
* @throws Exception
*/
@Test
public void testPasswordBasedSuccessfulAuth() throws Exception {
makeCallSecured("anil", "anil", 200);
makeCallWeaklySecured("anil", "anil", 200);
makeCallHardSecured("anil", "anil", 403);
}
/**
* <p>
* Test with user "marcus" who has the right password but does not have the right role.
* </p>
* <p>
* Should be a HTTP/403
* </p>
*
* @throws Exception
*/
@Test
public void testPasswordBasedUnsuccessfulAuth() throws Exception {
makeCallSecured("marcus", "marcus", 403);
makeCallWeaklySecured("marcus", "marcus", 200);
makeCallHardSecured("marcus", "marcus", 403);
}
/**
* <p>
* Test with non-existent user "non-existent-user".
* </p>
* <p>
* Should be a HTTP/403
* </p>
*
* @throws Exception
*/
@Test
public void testPasswordBasedUnsuccessfulAuthNonExistentUser() throws Exception {
makeCallSecured("non-existent-user", "non-existent-user", 401);
makeCallWeaklySecured("non-existent-user", "non-existent-user", 401);
makeCallHardSecured("non-existent-user", "non-existent-user", 403);
}
protected abstract void makeCallSecured(String user, String pass, int expectedCode) throws Exception;
protected abstract void makeCallWeaklySecured(String user, String pass, int expectedCode) throws Exception;
protected abstract void makeCallHardSecured(String user, String pass, int expectedCode) throws Exception;
/**
* Method that needs to be overridden with the HTTPClient code.
*
* @param user username
* @param pass password
* @param expectedCode http status code
* @throws Exception
*/
protected void makeCall(String user, String pass, int expectedCode, URL url) throws Exception {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
new UsernamePasswordCredentials(user, pass));
try (CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credentialsProvider)
.build()) {
HttpGet httpget = new HttpGet(url.toExternalForm());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
assertEquals(expectedCode, statusLine.getStatusCode());
EntityUtils.consume(entity);
}
}
}
| 5,157
| 36.376812
| 111
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/servlet3/LoginServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.servlet3;
import java.io.IOException;
import java.security.Principal;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* A simple servlet that tries to do a programmatic login
*
* @author <a href="mailto:mmoyses@redhat.com">Marcus Moyses</a>
*/
@WebServlet(name = "LoginServlet", urlPatterns = {"/login/"}, loadOnStartup = 1)
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 5442257117956926577L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = (String) req.getParameter("username");
String password = (String) req.getParameter("password");
req.login(username, password);
Principal principal = req.getUserPrincipal();
if (principal == null)
throw new ServletException("getUserPrincipal returned null");
String remoteUser = req.getRemoteUser();
if (remoteUser == null)
throw new ServletException("getRemoteUser returned null");
String authType = req.getAuthType();
if (authType == null || !(authType.equals("Programmatic") || "Programatic".equals(authType)))
throw new ServletException(String.format("getAuthType returned wrong type '%s'", authType));
if (!req.isUserInRole("gooduser")) {
resp.sendError(403);
}
req.logout();
principal = req.getUserPrincipal();
if (principal != null)
throw new ServletException("getUserPrincipal didn't return null after logout");
remoteUser = req.getRemoteUser();
if (remoteUser != null)
throw new ServletException("getRemoteUser didn't return null after logout");
authType = req.getAuthType();
if (authType != null)
throw new ServletException("getAuthType didn't return null after logout");
if (req.isUserInRole("gooduser") || req.isUserInRole("superuser"))
throw new ServletException("User shouldn't be in any roles after logout");
}
}
| 3,337
| 44.108108
| 113
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/servlet3/WebSecurityProgrammaticLoginTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.servlet3;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ContainerResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.categories.CommonCriteria;
import org.jboss.as.test.integration.security.WebSecurityPasswordBasedBase;
import org.jboss.as.test.integration.web.security.WebTestsSecurityDomainSetup;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
/**
* Unit Test the programmatic login feature of Servlet 3
*
* @author <a href="mailto:mmoyses@redhat.com">Marcus Moyses</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(WebTestsSecurityDomainSetup.class)
@Category(CommonCriteria.class)
public class WebSecurityProgrammaticLoginTestCase extends WebSecurityPasswordBasedBase {
private static final String warSuffix = ".war";
private static final String warName = "web-secure-programmatic-login";
@ContainerResource
private ManagementClient managementClient;
@Deployment
public static WebArchive deployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, warName + warSuffix);
war.addAsWebInfResource(WebSecurityProgrammaticLoginTestCase.class.getPackage(), "jboss-web.xml", "jboss-web" +
".xml");
war.addClass(LoginServlet.class);
war.addAsManifestResource(createPermissionsXmlAsset(new RuntimePermission("org.jboss.security.*")),
"permissions.xml");
return war;
}
protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpResponse res = httpclient.execute(new HttpGet(managementClient.getWebUri() + "/" + getContextPath() +
"/login/?username=" + user + "&password=" + pass));
Assert.assertEquals(expectedStatusCode, res.getStatusLine().getStatusCode());
}
}
public String getContextPath() {
return warName;
}
}
| 3,705
| 42.093023
| 119
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/servlet3/ServletSecurityRoleNamesAnnotationsTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.servlet3;
import java.net.URL;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.categories.CommonCriteria;
import org.jboss.as.test.integration.web.security.WebTestsSecurityDomainSetup;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
/**
* Unit Test the 'rolesAllowed' annotations defined in servlet work as expected.
*
* @author Jan Stourac
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(WebTestsSecurityDomainSetup.class)
@Category(CommonCriteria.class)
public class ServletSecurityRoleNamesAnnotationsTestCase extends ServletSecurityRoleNamesCommon {
private static final String warName = ServletSecurityRoleNamesAnnotationsTestCase.class.getName();
@ArquillianResource
protected URL url;
@Deployment
public static WebArchive deployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, warName + WAR_SUFFIX);
war.addAsWebInfResource(ServletSecurityRoleNamesTestCase.class.getPackage(), "jboss-web.xml", "jboss-web" +
".xml");
war.setWebXML(ServletSecurityRoleNamesTestCase.class.getPackage(), "role-names-annotations-web.xml");
war.addClass(RoleNamesAnnotationsServlet.RoleNamesAnnotationsSecuredServlet.class);
war.addClass(RoleNamesAnnotationsServlet.RoleNamesAnnotationsWeaklySecuredServlet.class);
war.addClass(RoleNamesAnnotationsServlet.RoleNamesAnnotationsHardSecuredServlet.class);
war.addPackage(CommonCriteria.class.getPackage());
return war;
}
protected void makeCallSecured(String user, String pass, int expectedCode) throws Exception {
makeCall(user, pass, expectedCode, new URL(url.toExternalForm() + SECURED_INDEX));
}
protected void makeCallWeaklySecured(String user, String pass, int expectedCode) throws Exception {
makeCall(user, pass, expectedCode, new URL(url.toExternalForm() + WEAKLY_SECURED_INDEX));
}
protected void makeCallHardSecured(String user, String pass, int expectedCode) throws Exception {
makeCall(user, pass, expectedCode, new URL(url.toExternalForm() + HARD_SECURED_INDEX));
}
}
| 3,554
| 44
| 115
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/digest/WebSecurityDIGESTTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2015, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.digest;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import java.net.URL;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.integration.security.WebSecurityPasswordBasedBase;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.SimpleSecuredServlet;
import org.jboss.as.test.integration.security.common.servlets.SimpleServlet;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Simple test case for web DIGEST authentication.
*
* @author olukas
*/
@RunWith(Arquillian.class)
@ServerSetup({WebSecurityDigestSecurityDomainSetup.class})
@RunAsClient
public class WebSecurityDIGESTTestCase extends WebSecurityPasswordBasedBase {
private static final String DEPLOYMENT = "digestApp";
private static final String WEB_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"\n" +
"<web-app xmlns=\"http://java.sun.com/xml/ns/javaee\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun" +
".com/xml/ns/javaee/web-app_3_0.xsd\"\n" +
" version=\"3.0\">\n" +
"\n" +
"\t<login-config>\n" +
"\t\t<auth-method>DIGEST</auth-method>\n" +
"\t\t<realm-name>" + WebSecurityDigestSecurityDomainSetup.SECURITY_DOMAIN_NAME + "</realm-name>\n" +
"\t</login-config>\n" +
"</web-app>";
@Deployment(name = DEPLOYMENT)
public static WebArchive deployment() throws Exception {
final WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT + ".war");
war.addClasses(SimpleServlet.class, SimpleSecuredServlet.class);
war.addAsWebInfResource(Utils.getJBossWebXmlAsset(WebSecurityDigestSecurityDomainSetup.SECURITY_DOMAIN_NAME),
"jboss-web.xml");
war.addAsWebInfResource(new StringAsset(WEB_XML), "web.xml");
return war;
}
@ArquillianResource
private URL url;
/**
* Check whether user with incorrect credentials has not access to secured page.
*
* @param url
* @throws Exception
*/
@OperateOnDeployment(DEPLOYMENT)
@Test
public void testWrongUser(@ArquillianResource URL url) throws Exception {
makeCall(WebSecurityDigestSecurityDomainSetup.GOOD_USER_NAME, WebSecurityDigestSecurityDomainSetup
.GOOD_USER_PASSWORD + "makeThisPasswordWrong", HTTP_UNAUTHORIZED);
}
/**
* Check that after successful login, the nonce can be re-used without an extra 401 Unauthorized response loop.
*
* @param url
* @throws Exception
*/
@OperateOnDeployment(DEPLOYMENT)
@Test
public void testFollowupRequest(@ArquillianResource URL url) throws Exception {
makeCallFollowup(WebSecurityDigestSecurityDomainSetup.GOOD_USER_NAME, WebSecurityDigestSecurityDomainSetup
.GOOD_USER_PASSWORD, HTTP_OK, true);
}
@Override
protected void makeCall(String user, String pass, int expectedCode) throws Exception {
makeCallFollowup(user, pass, expectedCode, false);
}
protected void makeCallFollowup(String user, String pass, int expectedCode, boolean followup) throws Exception {
final URL servletUrl = new URL(url.toExternalForm() + SimpleSecuredServlet.SERVLET_PATH.substring(1));
Utils.makeCallWithBasicAuthn(servletUrl, user, pass, expectedCode, followup);
}
}
| 5,116
| 41.641667
| 117
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/digest/WebSecurityDigestSecurityDomainSetup.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.digest;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.integration.management.util.CLIWrapper;
import org.jboss.as.test.integration.security.common.servlets.SimpleSecuredServlet;
import org.wildfly.test.security.common.elytron.PropertyFileBasedDomain;
import org.wildfly.test.security.common.elytron.UndertowDomainMapper;
/**
* Security domain setup for digest tests. This prepare either legacy security-domain or elytron configuration.
*
* @author olukas, jstourac
*/
public class WebSecurityDigestSecurityDomainSetup implements ServerSetupTask {
private CLIWrapper cli;
private PropertyFileBasedDomain ps;
private UndertowDomainMapper domainMapper;
protected static final String SECURITY_DOMAIN_NAME = "digestSecurityDomain";
protected static final String GOOD_USER_NAME = "anil";
protected static final String GOOD_USER_PASSWORD = "anil";
private static final String GOOD_USER_ROLE = SimpleSecuredServlet.ALLOWED_ROLE;
private static final String SUPER_USER_NAME = "marcus";
private static final String SUPER_USER_PASSWORD = "marcus";
private static final String SUPER_USER_ROLE = "superuser";
@Override
public void setup(ManagementClient managementClient, String s) throws Exception {
cli = new CLIWrapper(true);
setupElytronBasedSecurityDomain();
}
@Override
public void tearDown(ManagementClient managementClient, String s) throws Exception {
domainMapper.remove(cli);
ps.remove(cli);
cli.close();
}
private void setupElytronBasedSecurityDomain() throws Exception {
ps = PropertyFileBasedDomain.builder()
.withUser(GOOD_USER_NAME, GOOD_USER_PASSWORD, GOOD_USER_ROLE)
.withUser(SUPER_USER_NAME, SUPER_USER_PASSWORD, SUPER_USER_ROLE)
.withName(SECURITY_DOMAIN_NAME).build();
ps.create(cli);
domainMapper = UndertowDomainMapper.builder().withName(SECURITY_DOMAIN_NAME).build();
domainMapper.create(cli);
}
}
| 3,182
| 42.013514
| 111
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/tg/TransportGuaranteeServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.tg;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Testing servlet which enables transport guarantee security constraint.
*
* @author <a href="mailto:pskopek@redhat.com">Peter Skopek</a>
*/
public class TransportGuaranteeServlet extends HttpServlet {
private static final long serialVersionUID = 2L;
public static final String servletContext = "/tg/srv";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("TransportGuaranteedGet");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("TransportGuaranteedPost");
}
}
| 1,995
| 35.962963
| 114
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/tg/TransportGuaranteeMixedServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.tg;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HttpConstraint;
import jakarta.servlet.annotation.ServletSecurity;
import jakarta.servlet.annotation.ServletSecurity.TransportGuarantee;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Testing servlet which enables transport guarantee security constraint.
*
* @author <a href="mailto:pskopek@redhat.com">Peter Skopek</a>
*/
@WebServlet(name = "TG_MIXED_servlet", urlPatterns = {TransportGuaranteeMixedServlet.servletContext}, loadOnStartup = 1)
@ServletSecurity(@HttpConstraint(rolesAllowed = {"gooduser"}, transportGuarantee = TransportGuarantee.NONE))
public class TransportGuaranteeMixedServlet extends HttpServlet {
private static final long serialVersionUID = 3L;
public static final String servletContext = "/tg_mixed/srv";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("TransportGuaranteedGet");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("TransportGuaranteedPost");
}
}
| 2,453
| 39.9
| 120
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/tg/TransportGuaranteeAnnotatedServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.tg;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HttpConstraint;
import jakarta.servlet.annotation.ServletSecurity;
import jakarta.servlet.annotation.ServletSecurity.TransportGuarantee;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Testing servlet which enables transport guarantee security constraint.
*
* @author <a href="mailto:pskopek@redhat.com">Peter Skopek</a>
*/
@WebServlet(name = "TGSecuredServlet", urlPatterns = {TransportGuaranteeAnnotatedServlet.servletContext},
loadOnStartup = 1)
@ServletSecurity(@HttpConstraint(rolesAllowed = {"gooduser"}, transportGuarantee = TransportGuarantee.CONFIDENTIAL))
public class TransportGuaranteeAnnotatedServlet extends HttpServlet {
private static final long serialVersionUID = 2L;
public static final String servletContext = "/tg_ann/srv";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("TransportGuaranteedGet");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("TransportGuaranteedPost");
}
}
| 2,475
| 39.590164
| 116
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/tg/TransportGuaranteeTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.tg;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.OperationBuilder;
import org.jboss.as.test.categories.CommonCriteria;
import org.jboss.as.test.http.util.TestHttpClientUtils;
import org.jboss.as.test.integration.management.util.CLIWrapper;
import org.jboss.as.test.integration.web.security.WebTestsSecurityDomainSetup;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.test.security.common.elytron.CredentialReference;
import org.wildfly.test.security.common.elytron.Path;
import org.wildfly.test.security.common.elytron.SimpleKeyManager;
import org.wildfly.test.security.common.elytron.SimpleKeyStore;
import org.wildfly.test.security.common.elytron.SimpleServerSslContext;
import org.wildfly.test.security.common.other.SimpleSocketBinding;
import org.wildfly.test.undertow.common.elytron.SimpleHttpsListener;
/**
* This test case check if transport-guarantee security constraint works properly.
*
* @author <a href="mailto:pskopek@redhat.com">Peter Skopek</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({WebTestsSecurityDomainSetup.class, TransportGuaranteeTestCase.ListenerSetup.class})
@Category(CommonCriteria.class)
public class TransportGuaranteeTestCase {
private static final Logger log = Logger.getLogger(TransportGuaranteeTestCase.class);
private static final String WAR = ".war";
private static final String TG_ANN = "tg-annotated";
private static final String TG_DD = "tg-dd";
private static final String TG_MIXED = "tg-mixed";
private static String httpsTestURL = null;
private static String httpTestURL = null;
@Deployment(name = TG_ANN + WAR, order = 1, testable = false)
public static WebArchive deployAnnWar() throws Exception {
return getDeployment(TG_ANN);
}
@Deployment(name = TG_DD + WAR, order = 2, testable = false)
public static WebArchive deployDdWar() {
return getDeployment(TG_DD);
}
@Deployment(name = TG_MIXED + WAR, order = 3, testable = false)
public static WebArchive deployMixedWar() {
return getDeployment(TG_MIXED);
}
private static WebArchive getDeployment(String warName) {
log.trace("starting to deploy " + warName + ".war");
WebArchive war = ShrinkWrap.create(WebArchive.class, warName + WAR);
if (TG_MIXED.equals(warName)) {
war.addClass(TransportGuaranteeMixedServlet.class);
war.setWebXML(TransportGuaranteeTestCase.class.getPackage(), "mixed-web.xml");
} else if (TG_DD.equals(warName)) {
war.addClass(TransportGuaranteeServlet.class);
war.setWebXML(TransportGuaranteeTestCase.class.getPackage(), "dd-web.xml");
} else if (TG_ANN.equals(warName)) {
war.addClass(TransportGuaranteeAnnotatedServlet.class);
war.setWebXML(TransportGuaranteeTestCase.class.getPackage(), "annotated-web.xml");
}
war.addAsWebInfResource(TransportGuaranteeTestCase.class.getPackage(), "jboss-web.xml", "jboss-web.xml");
return war;
}
@Before
public void before() throws IOException {
// set test URL
httpsTestURL = "https://" + TestSuiteEnvironment.getHttpAddress() + ":" + Integer.toString
(TransportGuaranteeTestCase.ListenerSetup.HTTPS_PORT);
httpTestURL = "http://" + TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort();
}
@AfterClass
public static void after() throws IOException {
}
/**
* Check response on given url
*
* @param url
* @param responseSubstring - if null we are checking response code only
* @return
* @throws Exception
*/
private boolean checkGetURL(String url, String responseSubstring, String user, String pass) throws Exception {
log.trace("Checking URL=" + url);
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY),
new UsernamePasswordCredentials(user, pass));
CloseableHttpClient httpClient;
if (url.startsWith("https")) {
httpClient = TestHttpClientUtils.getHttpsClient(credentialsProvider);
} else {
httpClient = HttpClientBuilder.create()
.setDefaultCredentialsProvider(credentialsProvider)
.build();
}
HttpGet get = new HttpGet(url);
HttpResponse hr;
try {
try {
hr = httpClient.execute(get);
} catch (Exception e) {
if (responseSubstring == null) {
return false;
} else {
// in case substring is defined, rethrow exception so, we can easier analyze the cause
throw new Exception(e);
}
}
int statusCode = hr.getStatusLine().getStatusCode();
if (statusCode != 200) {
log.trace("statusCode not expected. statusCode=" + statusCode + ", URL=" + url);
return false;
}
if (responseSubstring == null) {
// this indicates that negative test had problems
log.trace("statusCode==200 on URL=" + url);
return true;
}
String response = EntityUtils.toString(hr.getEntity());
if (response.indexOf(responseSubstring) != -1) {
return true;
} else {
log.trace("Response doesn't contain expected substring (" + responseSubstring + ")");
return false;
}
} finally {
if (httpClient != null) {
httpClient.close();
}
}
}
@Test
public void testTransportGuaranteedAnnotation() throws Exception {
performRequestsAndCheck("/" + TG_ANN + TransportGuaranteeAnnotatedServlet.servletContext);
}
@Test
public void testTransportGuaranteedDD() throws Exception {
performRequestsAndCheck("/" + TG_DD + TransportGuaranteeServlet.servletContext);
}
@Test
public void testTransportGuaranteedMixed() throws Exception {
performRequestsAndCheck("/" + TG_MIXED + "/tg_mixed_override/srv");
}
private void performRequestsAndCheck(String testURLContext) throws Exception {
boolean result = checkGetURL(
httpsTestURL + testURLContext,
"TransportGuaranteedGet",
"anil",
"anil");
Assert.assertTrue("Not expected response", result);
result = checkGetURL(
httpTestURL + testURLContext,
null,
"anil",
"anil");
Assert.assertFalse("Non secure transport on URL has to be prevented, but was not", result);
}
static class ListenerSetup implements ServerSetupTask {
private static final Logger log = Logger.getLogger(ListenerSetup.class);
private static final String NAME = TransportGuaranteeTestCase.class.getSimpleName();
private static final File WORK_DIR = new File("target", "wildfly" + File.separator + "standalone" + File
.separator + "configuration");
private static final File SERVER_KEYSTORE_FILE = new File(WORK_DIR, "application.keystore");
private static final String PASSWORD = "password";
public static final int HTTPS_PORT = 8343;
private CLIWrapper cli;
private SimpleKeyStore simpleKeystore;
private SimpleKeyManager simpleKeyManager;
private SimpleServerSslContext simpleServerSslContext;
private SimpleSocketBinding simpleSocketBinding;
private SimpleHttpsListener simpleHttpsListener;
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
cli = new CLIWrapper(true);
setElytronBased(managementClient);
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
cli = new CLIWrapper(true);
simpleHttpsListener.remove(cli);
simpleSocketBinding.remove(cli);
simpleServerSslContext.remove(cli);
simpleKeyManager.remove(cli);
simpleKeystore.remove(cli);
}
protected void setElytronBased(ManagementClient managementClient) throws Exception {
setHttpsListenerSslContextBased(managementClient, cli, NAME, NAME, HTTPS_PORT, NAME, false);
}
private void setHttpsListenerSslContextBased(ManagementClient managementClient, CLIWrapper cli, String
httpsListenerName, String sockBindName, int httpsPort, String sslContext, boolean verifyClient) throws
Exception {
log.debug("start of the creation of the https-listener with ssl-context");
simpleKeystore = SimpleKeyStore.builder().withName(NAME)
.withPath(Path.builder().withPath(SERVER_KEYSTORE_FILE.getAbsolutePath()).build())
.withCredentialReference(CredentialReference.builder().withClearText(PASSWORD).build())
.build();
simpleKeystore.create(cli);
simpleKeyManager = SimpleKeyManager.builder().withName(NAME)
.withKeyStore(NAME)
.withCredentialReference(CredentialReference.builder().withClearText(PASSWORD).build())
.build();
simpleKeyManager.create(cli);
simpleServerSslContext = SimpleServerSslContext.builder().withName(sslContext)
.withKeyManagers(NAME)
.withProtocols("TLSv1.2")
.withNeedClientAuth(verifyClient)
.withAuthenticationOptional(false)
.build();
simpleServerSslContext.create(cli);
simpleSocketBinding = SimpleSocketBinding.builder().withName(sockBindName).withPort(httpsPort)
.build();
simpleSocketBinding.create(managementClient.getControllerClient(), cli);
simpleHttpsListener = SimpleHttpsListener.builder().withName(httpsListenerName).withSocketBinding
(sockBindName).
withSslContext(NAME).build();
simpleHttpsListener.create(cli);
log.debug("end of the ssl-context https-listener creation");
}
protected static void applyUpdates(final ModelControllerClient client, final List<ModelNode> updates) {
for (ModelNode update : updates) {
try {
applyUpdate(client, update, false);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
protected static void applyUpdate(final ModelControllerClient client, ModelNode update, boolean allowFailure)
throws IOException {
ModelNode result = client.execute(new OperationBuilder(update).build());
if (result.hasDefined("outcome") && (allowFailure || "success".equals(result.get("outcome").asString()))) {
if (result.hasDefined("result")) {
log.trace(result.get("result"));
}
} else if (result.hasDefined("failure-description")) {
throw new RuntimeException(result.get("failure-description").toString());
} else {
throw new RuntimeException("Operation not successful; outcome = " + result.get("outcome"));
}
}
}
}
| 13,996
| 41.544073
| 119
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/form/WebSecurityJBossWebXmlSecurityRolesTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.form;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.categories.CommonCriteria;
import org.jboss.as.test.integration.web.security.SecuredServlet;
import org.jboss.as.test.integration.web.security.WebTestsSecurityDomainSetup;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
/**
* Unit Test web security
*
* @author <a href="mailto:mmoyses@redhat.com">Marcus Moyses</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(WebTestsSecurityDomainSetup.class)
@Category(CommonCriteria.class)
@Ignore("AS7-6813 - Re-Evaluate or Remove WebSecurityJBossWebXmlSecurityRolesTestCase")
public class WebSecurityJBossWebXmlSecurityRolesTestCase extends AbstractWebSecurityFORMTestCase {
@Deployment(testable = false)
public static WebArchive deployment() throws Exception {
WebArchive war = ShrinkWrap.create(WebArchive.class, "web-secure.war");
war.addClasses(SecuredServlet.class);
war.addAsWebResource(WebSecurityJBossWebXmlSecurityRolesTestCase.class.getPackage(), "login.jsp", "login.jsp");
war.addAsWebResource(WebSecurityJBossWebXmlSecurityRolesTestCase.class.getPackage(), "error.jsp", "error.jsp");
war.addAsWebInfResource(WebSecurityJBossWebXmlSecurityRolesTestCase.class.getPackage(), "jboss-web-role-mapping.xml",
"jboss-web.xml");
war.addAsWebInfResource(WebSecurityJBossWebXmlSecurityRolesTestCase.class.getPackage(), "web.xml", "web.xml");
war.addAsResource(WebSecurityJBossWebXmlSecurityRolesTestCase.class.getPackage(), "users.properties",
"users.properties");
war.addAsResource(WebSecurityJBossWebXmlSecurityRolesTestCase.class.getPackage(), "roles.properties",
"roles.properties");
return war;
}
/**
* Negative test as marcus doesn't have proper role in module mapping created.
*/
@Override
@Test
public void testPasswordBasedUnsuccessfulAuth() throws Exception {
makeCall("marcus", "marcus", 200);
}
/**
* Negative test to see if mapping is not performed on username instead of role.
*
* @throws Exception
*/
@Test
public void testPrincipalMappingOnRole() throws Exception {
makeCall("peter", "peter", 403);
}
}
| 3,696
| 40.539326
| 125
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/form/AbstractWebSecurityFORMTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.form;
import static org.junit.Assert.assertEquals;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.security.WebSecurityPasswordBasedBase;
import org.jboss.as.test.integration.web.security.SecuredServlet;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
/**
* An Abstract parent of the FORM based authentication tests. <br/>
* <i>This class was introduced as a workaround for JBPAPP-9018 - {@link Class#getMethods()} method returns different
* values in
* Oracle JDK and IBM JDK.</i>
*
* @author Josef Cacek
*/
public abstract class AbstractWebSecurityFORMTestCase extends WebSecurityPasswordBasedBase {
private static Logger LOGGER = Logger.getLogger(AbstractWebSecurityFORMTestCase.class);
@ArquillianResource
private URL url;
// Protected methods -----------------------------------------------------
protected static WebArchive prepareDeployment(final String jbossWebFileName) throws Exception {
WebArchive war = ShrinkWrap.create(WebArchive.class, "web-secure.war");
war.addClasses(SecuredServlet.class);
war.addAsWebResource(WebSecurityFORMTestCase.class.getPackage(), "login.jsp", "login.jsp");
war.addAsWebResource(WebSecurityFORMTestCase.class.getPackage(), "error.jsp", "error.jsp");
war.addAsWebInfResource(WebSecurityFORMTestCase.class.getPackage(), jbossWebFileName, "jboss-web.xml");
war.addAsWebInfResource(WebSecurityFORMTestCase.class.getPackage(), "web.xml", "web.xml");
return war;
}
/**
* Makes a HTTP request to the protected web application.
*
* @param user
* @param pass
* @param expectedStatusCode
* @throws Exception
* @see WebSecurityPasswordBasedBase#makeCall(java.lang.String, java.lang.String,
* int)
*/
@Override
protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
String req = url.toExternalForm() + "secured/";
HttpGet httpget = new HttpGet(req);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
EntityUtils.consume(entity);
}
// We should get the Login Page
StatusLine statusLine = response.getStatusLine();
LOGGER.trace("Login form get: " + statusLine);
assertEquals(200, statusLine.getStatusCode());
LOGGER.trace("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
LOGGER.trace("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
LOGGER.trace("- " + cookies.get(i).toString());
}
}
req = url.toExternalForm() + "secured/j_security_check";
// We should now login with the user name and password
HttpPost httpPost = new HttpPost(req);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("j_username", user));
nvps.add(new BasicNameValuePair("j_password", pass));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
response = httpclient.execute(httpPost);
entity = response.getEntity();
if (entity != null) {
EntityUtils.consume(entity);
}
statusLine = response.getStatusLine();
// Post authentication - we have a 302
assertEquals(302, statusLine.getStatusCode());
Header locationHeader = response.getFirstHeader("Location");
String location = locationHeader.getValue();
HttpGet httpGet = new HttpGet(location);
response = httpclient.execute(httpGet);
entity = response.getEntity();
if (entity != null) {
EntityUtils.consume(entity);
}
LOGGER.trace("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
LOGGER.trace("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
LOGGER.trace("- " + cookies.get(i).toString());
}
}
// Either the authentication passed or failed based on the expected status code
statusLine = response.getStatusLine();
assertEquals(expectedStatusCode, statusLine.getStatusCode());
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| 6,797
| 38.988235
| 117
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/form/WebSecurityFORMTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.form;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.categories.CommonCriteria;
import org.jboss.as.test.integration.web.security.WebTestsSecurityDomainSetup;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
/**
* Unit Test web security
*
* @author Anil Saldhana
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(WebTestsSecurityDomainSetup.class)
@Category(CommonCriteria.class)
public class WebSecurityFORMTestCase extends AbstractWebSecurityFORMTestCase {
@Deployment
public static WebArchive deployment() throws Exception {
return prepareDeployment("jboss-web.xml");
}
}
| 1,960
| 39.020408
| 78
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/form/WebSecurityJBossWebSimpleRoleMappingTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.form;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.categories.CommonCriteria;
import org.jboss.as.test.integration.web.security.WebTestsSecurityDomainSetup;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
/**
* Unit Test web security
*
* @author <a href="mailto:pskopek@redhat.com">Peter Skopek</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(WebTestsSecurityDomainSetup.class)
@Category(CommonCriteria.class)
public class WebSecurityJBossWebSimpleRoleMappingTestCase extends AbstractWebSecurityFORMTestCase {
@Deployment(testable = false)
public static WebArchive deployment() throws Exception {
return prepareDeployment("jboss-web-role-mapping.xml");
}
/**
* At this time peter can go through because he has role mapped in the map-module option.
*
* @throws Exception
*/
@Test
public void testPrincipalMappingOnRole() throws Exception {
makeCall("peter", "peter", 200);
}
}
| 2,338
| 37.983333
| 99
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/websocket/SecuredEndpoint.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.websocket;
import jakarta.websocket.OnMessage;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
/**
* @author Stuart Douglas
*/
@ServerEndpoint("/websocket")
public class SecuredEndpoint {
@OnMessage
public String message(String message, Session session) {
return message + " " + session.getUserPrincipal();
}
}
| 1,449
| 35.25
| 70
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/websocket/WebSocketSecurityTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.websocket;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.net.SocketPermission;
import java.net.URI;
import java.util.PropertyPermission;
import jakarta.websocket.ContainerProvider;
import jakarta.websocket.DeploymentException;
import jakarta.websocket.WebSocketContainer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.integration.security.WebSecurityPasswordBasedBase;
import org.jboss.as.test.integration.web.security.WebTestsSecurityDomainSetup;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.runner.RunWith;
/**
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
@ServerSetup(WebTestsSecurityDomainSetup.class)
@RunAsClient
public class WebSocketSecurityTestCase extends WebSecurityPasswordBasedBase {
@Deployment
public static WebArchive deploy() {
return ShrinkWrap.create(WebArchive.class, "websocket.war")
.addPackage(WebSocketSecurityTestCase.class.getPackage())
.addAsWebInfResource(WebSocketSecurityTestCase.class.getPackage(), "jboss-web.xml", "jboss-web.xml")
.addAsWebInfResource(WebSocketSecurityTestCase.class.getPackage(), "web.xml", "web.xml")
.addClass(TestSuiteEnvironment.class)
.addAsManifestResource(
createPermissionsXmlAsset(
// Needed for the TestSuiteEnvironment.getServerAddress()
new PropertyPermission("management.address", "read"),
new PropertyPermission("node0", "read"),
new PropertyPermission("jboss.http.port", "read"),
// Needed for the serverContainer.connectToServer()
new SocketPermission("*:" + TestSuiteEnvironment.getHttpPort(), "connect,resolve")
), "permissions.xml")
.addAsManifestResource(new StringAsset("io.undertow.websockets.jsr.UndertowContainerProvider"),
"services/jakarta.websocket.ContainerProvider");
}
@Override
protected void makeCall(final String user, final String pass, final int expectedCode) throws Exception {
AnnotatedClient endpoint = new AnnotatedClient();
endpoint.setCredentials(user, pass);
WebSocketContainer serverContainer = ContainerProvider.getWebSocketContainer();
if (expectedCode == 200) {
connectToServer(serverContainer, endpoint);
Assert.assertEquals("Hello anil", endpoint.getMessage());
} else {
boolean exceptionThrown = false;
try {
connectToServer(serverContainer, endpoint);
} catch (DeploymentException e) {
exceptionThrown = true;
} finally {
Assert.assertTrue("We expected that 'DeploymentException' is thrown as we provided incorrect " +
"credentials to ws endpoint.", exceptionThrown);
}
}
}
private void connectToServer(WebSocketContainer serverContainer, AnnotatedClient endpoint) throws Exception {
serverContainer.connectToServer(endpoint, new URI("ws", "", TestSuiteEnvironment.getServerAddress(),
TestSuiteEnvironment.getHttpPort(), "/websocket/websocket", "", ""));
}
}
| 4,847
| 46.529412
| 116
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/websocket/AnnotatedClient.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.websocket;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import jakarta.websocket.ClientEndpoint;
import jakarta.websocket.ClientEndpointConfig;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import io.undertow.util.FlexBase64;
/**
* @author Stuart Douglas
*/
@ClientEndpoint(configurator = AnnotatedClient.AuthConfigurator.class)
public class AnnotatedClient {
private static String user;
private static String password;
private final BlockingDeque<String> queue = new LinkedBlockingDeque<>();
@OnOpen
public void open(final Session session) throws IOException {
session.getBasicRemote().sendText("Hello");
}
@OnMessage
public void message(final String message) {
queue.add(message);
}
public String getMessage() throws InterruptedException {
return queue.poll(5, TimeUnit.SECONDS);
}
public void setCredentials(String user, String password) {
this.user = user;
this.password = password;
}
public static class AuthConfigurator extends ClientEndpointConfig.Configurator {
@Override
public void beforeRequest(Map<String, List<String>> headers) {
String credentials = user + ":" + password;
headers.put("AUTHORIZATION", Collections.singletonList("Basic " + FlexBase64.encodeString(credentials
.getBytes(StandardCharsets.UTF_8), false)));
}
}
}
| 2,785
| 34.265823
| 113
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/basic/WebSecurityBASICTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.security.basic;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.categories.CommonCriteria;
import org.jboss.as.test.integration.security.WebSecurityPasswordBasedBase;
import org.jboss.as.test.integration.web.security.SecuredServlet;
import org.jboss.as.test.integration.web.security.WebTestsSecurityDomainSetup;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
/**
* Unit Test the BASIC authentication
*
* @author Anil Saldhana
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(WebTestsSecurityDomainSetup.class)
@Category(CommonCriteria.class)
public class WebSecurityBASICTestCase extends WebSecurityPasswordBasedBase {
private static final Logger log = Logger.getLogger(WebSecurityBASICTestCase.class);
private static final String JBOSS_WEB_CONTENT = "<?xml version=\"1.0\"?>\n" +
"<jboss-web>\n" +
" <security-domain>" + WebTestsSecurityDomainSetup.WEB_SECURITY_DOMAIN + "</security-domain>\n" +
"</jboss-web>";
@Deployment
public static WebArchive deployment() throws Exception {
WebArchive war = ShrinkWrap.create(WebArchive.class, "web-secure-basic.war");
war.addClass(SecuredServlet.class);
war.addAsWebInfResource(new StringAsset(JBOSS_WEB_CONTENT), "jboss-web.xml");
war.addAsWebInfResource(WebSecurityBASICTestCase.class.getPackage(), "web.xml", "web.xml");
return war;
}
@ArquillianResource
private URL url;
@Override
protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
new UsernamePasswordCredentials(user, pass));
try (CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credentialsProvider)
.build()) {
HttpGet httpget = new HttpGet(url.toExternalForm() + "secured/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
if (entity != null) {
log.trace("Response content length: " + entity.getContentLength());
}
assertEquals(expectedStatusCode, statusLine.getStatusCode());
if (200 == expectedStatusCode) {
// check only in case authentication was successfull
checkResponsecontent(EntityUtils.toString(entity), user, pass);
}
EntityUtils.consume(entity);
}
}
private void checkResponsecontent(String response, String user, String password) {
assertNotNull("Response is 'null', we expected non-null response!", response);
assertTrue("Remote user different from what we expected!", response.contains("Remote user: " + user));
assertTrue("User principal different from what we expected!", response.contains("User principal: " + password));
assertTrue("Authentication type different from what we expected!", response.contains("Authentication type: " +
"BASIC"));
}
}
| 5,437
| 43.211382
| 120
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/threads/RaceyServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.threads;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
/**
*/
@WebServlet(name = "RaceyServlet", urlPatterns = {"/race"})
public class RaceyServlet extends HttpServlet {
private int value;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int value = this.value;
//incremement the value, with a little sleep to increase the chance of a racey update
try {
Thread.sleep(2);
} catch (InterruptedException e) {
}
this.value = value + 1;
Writer writer = resp.getWriter();
writer.write("" + value);
}
}
| 1,964
| 36.075472
| 113
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/threads/ServletThreadPoolSelectionTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.threads;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.*;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.junit.Assert.assertEquals;
/**
* Tests the use of a custom thread pool with servlet deployments.
* <p/>
* This creates an executor with a single thread, and then invokes RaceyServlet
* multiple times from several threads. If it is not using the correct
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(ServletThreadPoolSelectionTestCase.ServletThreadPoolSelectionTestCaseSetupAction.class)
public class ServletThreadPoolSelectionTestCase {
public static class ServletThreadPoolSelectionTestCaseSetupAction implements ServerSetupTask {
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
ModelNode op;
op = new ModelNode();
op.get(OP).set(ADD);
op.get(OP_ADDR).add(SUBSYSTEM, "io");
op.get(OP_ADDR).add("worker", "test-worker");
op.get("task-max-threads").set(1);
managementClient.getControllerClient().execute(op);
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
ModelNode op;
op = new ModelNode();
op.get(OP).set(REMOVE);
op.get(OP_ADDR).add(SUBSYSTEM, "io");
op.get(OP_ADDR).add("worker", "test-worker");
managementClient.getControllerClient().execute(op);
}
}
@ArquillianResource
private URL url;
@Deployment
public static WebArchive deployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "war-example.war");
war.addClasses(HttpRequest.class, RaceyServlet.class);
war.addAsWebInfResource(ServletThreadPoolSelectionTestCase.class.getPackage(), "jboss-web.xml", "jboss-web.xml");
return war;
}
@Test
public void testExecutor() throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(10);
try {
final List<Future<?>> results = new ArrayList<Future<?>>();
for (int i = 0; i < 100; ++i) {
results.add(executor.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
HttpRequest.get(url.toExternalForm() + "/race", 10, SECONDS);
return null;
}
}));
}
for (Future<?> res : results) {
res.get();
}
String result = HttpRequest.get(url.toExternalForm() + "/race", 10, SECONDS);
assertEquals("100", result);
} finally {
executor.shutdown();
}
}
}
| 4,855
| 38.16129
| 121
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/sso/SingleSignOnUnitTestCase.java
|
/*
* JBoss, a division of Red Hat
* Copyright 2006, Red Hat Middleware, LLC, and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.sso;
import java.net.URL;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.categories.CommonCriteria;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
/**
* Tests of web app single sign-on
*
* @author Scott.Stark@jboss.org
* @author lbarreiro@redhat.com
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(SingleSignOnUnitTestCase.SingleSignOnUnitTestCaseSetup.class)
@Ignore(value = "ARQ-791 Arquillian is unable to reconnect to JMX server if the connection is lost")
@Category(CommonCriteria.class)
public class SingleSignOnUnitTestCase {
private static Logger log = Logger.getLogger(SingleSignOnUnitTestCase.class);
static class SingleSignOnUnitTestCaseSetup implements ServerSetupTask {
public void setup(final ManagementClient managementClient, final String containerId) throws Exception {
SSOTestBase.addSso(managementClient.getControllerClient());
SSOTestBase.restartServer(managementClient.getControllerClient());
}
public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception {
SSOTestBase.removeSso(managementClient.getControllerClient());
}
}
/**
* One time setup for all SingleSignOnUnitTestCase unit tests
*/
@Deployment(name = "web-sso.ear", testable = false)
public static EnterpriseArchive deployment() {
return SSOTestBase.createSsoEar();
}
/**
* Test single sign-on across two web apps using form based auth
*/
@Test
public void testFormAuthSingleSignOn(@ArquillianResource URL baseURLNoAuth) throws Exception {
log.trace("+++ testFormAuthSingleSignOn");
SSOTestBase.executeFormAuthSingleSignOnTest(baseURLNoAuth, baseURLNoAuth, log);
}
/**
* Test single sign-on across two web apps using form based auth
*/
@Test
public void testNoAuthSingleSignOn(@ArquillianResource URL baseURLNoAuth) throws Exception {
log.trace("+++ testNoAuthSingleSignOn");
SSOTestBase.executeNoAuthSingleSignOnTest(baseURLNoAuth, baseURLNoAuth, log);
}
}
| 3,697
| 37.926316
| 114
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/reverseproxy/ServerNameServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.reverseproxy;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
*/
@WebServlet(name = "ServerNameServlet", urlPatterns = {"/name"})
public class ServerNameServlet extends HttpServlet {
private String message;
@Override
public void init(ServletConfig config) throws ServletException {
message = config.getInitParameter("message");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if("true".equals(req.getParameter("session"))) {
req.getSession(true);
}
if (req.getParameter("wait") != null) {
try {
Thread.sleep(Long.parseLong(req.getParameter("wait")));
} catch (InterruptedException e) {}
}
resp.getWriter().write(message);
resp.getWriter().close();
}
}
| 2,187
| 34.868852
| 113
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/reverseproxy/CookieListener.java
|
package org.jboss.as.test.integration.web.reverseproxy;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;
/**
* @author Stuart Douglas
*/
@WebListener
public class CookieListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
sce.getServletContext().getSessionCookieConfig().setPath("/");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
| 543
| 24.904762
| 70
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/reverseproxy/ReverseProxyTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.reverseproxy;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ContainerResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.integration.management.ManagementOperations;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALLOW_RESOURCE_SERVICE_RESTART;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS;
import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode;
import org.jboss.as.test.shared.ServerReload;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
/**
*/
@RunWith(Arquillian.class)
@RunAsClient
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ReverseProxyTestCase {
@ContainerResource
private ManagementClient managementClient;
private static ManagementClient mc;
@Before
public void setup() throws Exception {
if (mc == null) {
mc = managementClient;
//add the reverse proxy
ModelNode op = new ModelNode();
ModelNode addr = new ModelNode();
addr.add(ModelDescriptionConstants.SUBSYSTEM, "undertow");
addr.add("configuration", "handler");
addr.add("reverse-proxy", "myproxy");
op.get(ModelDescriptionConstants.OP_ADDR).set(addr);
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD);
op.get("max-request-time").set(60000);
op.get("connection-idle-timeout").set(60000);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
//add the hosts
ModelNode addSocketBindingOp = getOutboundSocketBinding(managementClient.getWebUri().getHost(), managementClient.getWebUri().getPort());
ManagementOperations.executeOperation(managementClient.getControllerClient(),addSocketBindingOp);
op = new ModelNode();
addr = new ModelNode();
addr.add(ModelDescriptionConstants.SUBSYSTEM, "undertow");
addr.add("configuration", "handler");
addr.add("reverse-proxy", "myproxy");
addr.add("host", "server1");
op.get(ModelDescriptionConstants.OP_ADDR).set(addr);
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD);
op.get("outbound-socket-binding").set("proxy-host");
op.get("path").set("/server1");
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
op = new ModelNode();
addr = new ModelNode();
addr.add(ModelDescriptionConstants.SUBSYSTEM, "undertow");
addr.add("configuration", "handler");
addr.add("reverse-proxy", "myproxy");
addr.add("host", "server2");
op.get(ModelDescriptionConstants.OP_ADDR).set(addr);
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD);
op.get("outbound-socket-binding").set("proxy-host");
op.get("path").set("/server2");
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
op = new ModelNode();
addr = new ModelNode();
addr.add(ModelDescriptionConstants.SUBSYSTEM, "undertow");
addr.add("server", "default-server");
addr.add("host", "default-host");
addr.add("location", "/proxy");
op.get(ModelDescriptionConstants.OP_ADDR).set(addr);
op.get("handler").set("myproxy");
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
}
}
private static ModelNode getOutboundSocketBinding(String address, int port) {
ModelNode op = createOpNode("socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=proxy-host", "add");
op.get("host").set(address);
op.get("port").set(port);
return op;
}
@AfterClass
public static void tearDown() throws Exception {
ModelNode op = new ModelNode();
ModelNode addr = new ModelNode();
addr.add(ModelDescriptionConstants.SUBSYSTEM, "undertow");
addr.add("configuration", "handler");
addr.add("reverse-proxy", "myproxy");
addr.add("host", "server2");
op.get(ModelDescriptionConstants.OP_ADDR).set(addr);
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.REMOVE);
op.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true);
ManagementOperations.executeOperation(mc.getControllerClient(), op);
op = new ModelNode();
addr = new ModelNode();
addr.add(ModelDescriptionConstants.SUBSYSTEM, "undertow");
addr.add("configuration", "handler");
addr.add("reverse-proxy", "myproxy");
addr.add("host", "server1");
op.get(ModelDescriptionConstants.OP_ADDR).set(addr);
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.REMOVE);
op.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true);
ManagementOperations.executeOperation(mc.getControllerClient(), op);
op = new ModelNode();
addr = new ModelNode();
addr.add(ModelDescriptionConstants.SUBSYSTEM, "undertow");
addr.add("server", "default-server");
addr.add("host", "default-host");
addr.add("location", "/proxy");
op.get(ModelDescriptionConstants.OP_ADDR).set(addr);
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.REMOVE);
op.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true);
ManagementOperations.executeOperation(mc.getControllerClient(), op);
op = new ModelNode();
addr = new ModelNode();
addr.add(ModelDescriptionConstants.SUBSYSTEM, "undertow");
addr.add("configuration", "handler");
addr.add("reverse-proxy", "myproxy");
op.get(ModelDescriptionConstants.OP_ADDR).set(addr);
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.REMOVE);
op.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true);
ManagementOperations.executeOperation(mc.getControllerClient(), op);
op = createOpNode("socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=proxy-host", "remove");
ManagementOperations.executeOperation(mc.getControllerClient(), op);
}
@ArquillianResource
@OperateOnDeployment("server1")
private URL url;
@Deployment(name = "server1", testable = false)
public static WebArchive server1() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "server1.war");
war.addClasses(ServerNameServlet.class, CookieListener.class);
war.addAsWebInfResource(ReverseProxyTestCase.class.getPackage(), "web-server1.xml", "web.xml");
return war;
}
@Deployment(name = "server2", testable = false)
public static WebArchive server2() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "server2.war");
war.addClasses(ServerNameServlet.class, CookieListener.class);
war.addAsWebInfResource(ReverseProxyTestCase.class.getPackage(), "web-server2.xml", "web.xml");
return war;
}
private String performCall(CloseableHttpClient httpclient, String urlPattern) throws Exception {
HttpResponse res = httpclient.execute(new HttpGet("http://" + url.getHost() + ":" + url.getPort() + "/proxy/" + urlPattern));
Assert.assertEquals(200, res.getStatusLine().getStatusCode());
return EntityUtils.toString(res.getEntity());
}
@Test
public void testReverseProxy() throws Exception {
try (CloseableHttpClient httpclient = HttpClients.createDefault()){
final Set<String> results = new HashSet<>();
for (int i = 0; i < 10; ++i) {
results.add(performCall(httpclient,"name"));
}
Assert.assertEquals(2, results.size());
Assert.assertTrue(results.contains("server1"));
Assert.assertTrue(results.contains("server2"));
//TODO: re-add JVM route based sticky session testing
//String session = performCall("name?session=true");
//sticky sessions should stick it to this node
//for (int i = 0; i < 10; ++i) {
// Assert.assertEquals(session, performCall("name"));
//}
}
}
private void configureMaxRequestTime(int value) throws Exception {
ModelNode op = new ModelNode();
op.get(ModelDescriptionConstants.OP_ADDR).add(ModelDescriptionConstants.SUBSYSTEM, "undertow");
op.get(ModelDescriptionConstants.OP_ADDR).add("configuration", "handler");
op.get(ModelDescriptionConstants.OP_ADDR).add("reverse-proxy", "myproxy");
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION);
op.get(ModelDescriptionConstants.NAME).set("max-request-time");
op.get(ModelDescriptionConstants.VALUE).set(value);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
ServerReload.reloadIfRequired(managementClient);
}
@Test
public void testReverseProxyMaxRequestTime() throws Exception {
// set the max-request-time to a lower value than the wait
configureMaxRequestTime(10);
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpResponse res = httpclient.execute(new HttpGet("http://" + url.getHost() + ":" + url.getPort() + "/proxy/name?wait=50"));
// With https://issues.redhat.com/browse/UNDERTOW-1459 fix, status code should be 504
// FIXME: after undertow 2.2.13.Final integrated into WildFly full, this should be updated to 504 only
Assert.assertTrue("Service Unaviable expected because max-request-time is set to 10ms", res.getStatusLine().getStatusCode() == 504 || res.getStatusLine().getStatusCode() == 503);
}
}
}
| 12,189
| 46.431907
| 190
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/sharedsession/SharedSessionTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.sharedsession;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.http.util.TestHttpClientUtils;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
@RunAsClient
public class SharedSessionTestCase {
private static final String EAR_DEPLOYMENT_SHARED_SESSIONS = "sharedSession.ear";
private static final String EAR_DEPLOYMENT_NOT_SHARED_SESSIONS = "notSharedSession.ear";
@Deployment(name = EAR_DEPLOYMENT_SHARED_SESSIONS)
public static Archive<?> sharedSessionEarDeployment() {
WebArchive war1 = ShrinkWrap.create(WebArchive.class, "war1.war")
.addClass(SharedSessionServlet.class);
WebArchive war2 = ShrinkWrap.create(WebArchive.class, "war2.war")
.addClass(SharedSessionServlet.class);
EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_SHARED_SESSIONS)
.addAsModule(war1)
.addAsModule(war2)
.addAsManifestResource(SharedSessionTestCase.class.getPackage(), "jboss-all.xml", "jboss-all.xml");
return ear;
}
@Deployment(name = EAR_DEPLOYMENT_NOT_SHARED_SESSIONS)
public static Archive<?> notSharedEarDeployment() {
WebArchive war1 = ShrinkWrap.create(WebArchive.class, "warX.war")
.addClass(SharedSessionServlet.class);
WebArchive war2 = ShrinkWrap.create(WebArchive.class, "warY.war")
.addClass(SharedSessionServlet.class);
EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_NOT_SHARED_SESSIONS)
.addAsModule(war1)
.addAsModule(war2);
return ear;
}
/**
* Covers test case when there is EAR with enabled session sharing
*/
@Test
@OperateOnDeployment(EAR_DEPLOYMENT_SHARED_SESSIONS)
public void testSharedSessionsOneEar() throws IOException {
// Note that this test should not need to use a relaxed domain handling, however the http client does not treat ipv6 domains (e.g. ::1) properly
HttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient();
HttpGet get1 = new HttpGet("http://" + TestSuiteEnvironment.getServerAddress() + ":8080/war1/SharedSessionServlet");
HttpGet get2 = new HttpGet("http://" + TestSuiteEnvironment.getServerAddress() + ":8080/war2/SharedSessionServlet");
String result = runGet(get1, client);
assertEquals("0", result);
result = runGet(get1, client);
assertEquals("1", result);
result = runGet(get2, client);
assertEquals("2", result);
result = runGet(get2, client);
assertEquals("3", result);
result = runGet(get1, client);
assertEquals("4", result);
HttpClientUtils.closeQuietly(client);
}
private String runGet(HttpGet get, HttpClient client) throws IOException {
HttpResponse res = client.execute(get);
return EntityUtils.toString(res.getEntity());
}
/**
* Covers test case when there is EAR with disabled session sharing
*/
@Test
@OperateOnDeployment(EAR_DEPLOYMENT_NOT_SHARED_SESSIONS)
public void testNotSharedSessions() throws IOException {
// Note that this test should not need to use a relaxed domain handling, however the http client does not treat ipv6 domains (e.g. ::1) properly
HttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient();
HttpGet getX = new HttpGet("http://" + TestSuiteEnvironment.getServerAddress() + ":8080/warX/SharedSessionServlet");
HttpGet getY = new HttpGet("http://" + TestSuiteEnvironment.getServerAddress() + ":8080/warY/SharedSessionServlet");
String result = runGet(getX, client);
assertEquals("0", result);
result = runGet(getX, client);
assertEquals("1", result);
result = runGet(getY, client);
assertEquals("0", result);
result = runGet(getY, client);
assertEquals("1", result);
result = runGet(getX, client);
assertEquals("2", result);
HttpClientUtils.closeQuietly(client);
}
/**
* Covers test case when there is one ear with shared sessions between wars and second without sharing.
* This test checks that the sessions sharing in one EAR doesn't intervene with sessions in second EAR
*/
@Test
public void testSharedSessionsDoNotInterleave() throws IOException {
// Note that this test should not need to use a relaxed domain handling, however the http client does not treat ipv6 domains (e.g. ::1) properly
HttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient();
HttpGet get1 = new HttpGet("http://" + TestSuiteEnvironment.getServerAddress() + ":8080/war1/SharedSessionServlet");
HttpGet get2 = new HttpGet("http://" + TestSuiteEnvironment.getServerAddress() + ":8080/war2/SharedSessionServlet");
HttpGet getX = new HttpGet("http://" + TestSuiteEnvironment.getServerAddress() + ":8080/warX/SharedSessionServlet");
HttpGet getY = new HttpGet("http://" + TestSuiteEnvironment.getServerAddress() + ":8080/warY/SharedSessionServlet");
String result = runGet(get1, client);
assertEquals("0", result);
result = runGet(get2, client);
assertEquals("1", result);
result = runGet(getX, client);
assertEquals("0", result);
result = runGet(getY, client);
assertEquals("0", result);
result = runGet(get1, client);
assertEquals("2", result);
HttpClientUtils.closeQuietly(client);
}
}
| 7,439
| 44.644172
| 152
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/sharedsession/SharedSessionServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.sharedsession;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
/**
*/
@WebServlet(name = "SharedSessionServlet", urlPatterns = {"/SharedSessionServlet"})
public class SharedSessionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession(true);
Integer val = (Integer) session.getAttribute("val");
if (val == null) {
session.setAttribute("val", 0);
resp.getWriter().print(0);
} else {
session.setAttribute("val", ++val);
resp.getWriter().print(val);
}
}
}
| 2,006
| 37.596154
| 113
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/session/SessionTestServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.session;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
/**
*/
@WebServlet(name = "SessionPersistenceServlet", urlPatterns = {"/SessionPersistenceServlet"})
public class SessionTestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if(req.getParameter("invalidate") != null) {
req.getSession().invalidate();
} else {
HttpSession session = req.getSession(true);
Integer val = (Integer) session.getAttribute("val");
if (val == null) {
session.setAttribute("val", 0);
resp.getWriter().print(0);
} else {
session.setAttribute("val", ++val);
resp.getWriter().print(val);
}
}
}
}
| 2,167
| 37.714286
| 113
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/session/SessionInvalidateTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 2110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.session;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
*/
@RunWith(Arquillian.class)
@RunAsClient
public class SessionInvalidateTestCase {
@ArquillianResource
public ManagementClient managementClient;
@Deployment
public static Archive<?> dependent() {
return ShrinkWrap.create(WebArchive.class, "invalidate.war")
.addClasses(SessionTestServlet.class);
}
@Test
public void testInvalidateSessions() throws Exception {
try (CloseableHttpClient client = HttpClients.createDefault()) {
ModelNode operation = new ModelNode();
operation.get(ModelDescriptionConstants.OP).set("invalidate-session");
operation.get(ModelDescriptionConstants.OP_ADDR).set(PathAddress.parseCLIStyleAddress("/deployment=invalidate.war/subsystem=undertow").toModelNode());
operation.get("session-id").set("fake");
ModelNode opRes = managementClient.getControllerClient().execute(operation);
Assert.assertEquals("success", opRes.get(ModelDescriptionConstants.OUTCOME).asString());
Assert.assertEquals(false, opRes.get(ModelDescriptionConstants.RESULT).asBoolean());
HttpGet get = new HttpGet("http://" + TestSuiteEnvironment.getServerAddress() + ":8080/invalidate/SessionPersistenceServlet");
HttpResponse res = client.execute(get);
String sessionId = null;
for (Header cookie : res.getHeaders("Set-Cookie")) {
if (cookie.getValue().startsWith("JSESSIONID=")) {
sessionId = cookie.getValue().split("=")[1].split("\\.")[0];
break;
}
}
Assert.assertNotNull(sessionId);
String result = EntityUtils.toString(res.getEntity());
assertEquals("0", result);
result = runGet(get, client);
assertEquals("1", result);
result = runGet(get, client);
assertEquals("2", result);
operation.get("session-id").set(sessionId);
opRes = managementClient.getControllerClient().execute(operation);
Assert.assertEquals("success", opRes.get(ModelDescriptionConstants.OUTCOME).asString());
Assert.assertEquals(true, opRes.get(ModelDescriptionConstants.RESULT).asBoolean());
result = runGet(get, client);
assertEquals("0", result);
result = runGet(get, client);
assertEquals("1", result);
}
}
private String runGet(HttpGet get, HttpClient client) throws IOException {
HttpResponse res = client.execute(get);
return EntityUtils.toString(res.getEntity());
}
}
| 4,797
| 41.839286
| 162
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/session/SessionPersistenceTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.session;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
/**
*/
@RunWith(Arquillian.class)
@RunAsClient
@Ignore
public class SessionPersistenceTestCase {
@ArquillianResource
public Deployer deployer;
@Deployment(name = "web", managed = false, testable = false)
public static Archive<?> dependent() {
return ShrinkWrap.create(WebArchive.class, "sessionPersistence.war")
.addClasses(SessionTestServlet.class);
}
@Test
public void testLifeCycle() throws Exception {
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpGet get = new HttpGet("http://" + TestSuiteEnvironment.getServerAddress() + ":8080/sessionPersistence/SessionPersistenceServlet");
deployer.deploy("web");
String result = runGet(get, client);
assertEquals("0", result);
result = runGet(get, client);
assertEquals("1", result);
result = runGet(get, client);
assertEquals("2", result);
deployer.undeploy("web");
deployer.deploy("web");
result = runGet(get, client);
assertEquals("3", result);
result = runGet(get, client);
assertEquals("4", result);
}
}
private String runGet(HttpGet get, HttpClient client) throws IOException {
HttpResponse res = client.execute(get);
return EntityUtils.toString(res.getEntity());
}
}
| 3,385
| 37.044944
| 146
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/session/SessionStatisticsTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 2110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.session;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.integration.management.ManagementOperations;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.as.test.shared.SnapshotRestoreSetupTask;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.xnio.IoUtils;
import io.undertow.util.StatusCodes;
/**
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(SessionStatisticsTestCase.SessionStatisticsServerSetup.class)
public class SessionStatisticsTestCase {
private static final String ACTIVE_SESSIONS = "active-sessions";
private static final String EXPIRED_SESSIONS = "expired-sessions";
private static final String HIGHEST_SESSION_COUNT = "highest-session-count";
private static final String MAX_ACTIVE_SESSIONS = "max-active-sessions";
private static final String REJECTED_SESSIONS = "rejected-sessions";
private static final String SESSIONS_CREATED = "sessions-created";
private static final int CLIENT_COUNT = 7;
private static final int MAX_SESSIONS = 4;
@ArquillianResource
public ManagementClient managementClient;
static class SessionStatisticsServerSetup extends SnapshotRestoreSetupTask {
@Override
public void doSetup(ManagementClient managementClient, String containerId) throws Exception {
ModelNode op = new ModelNode();
op.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
op.get(OP_ADDR).add(SUBSYSTEM, "undertow");
op.get(NAME).set("statistics-enabled");
op.get(VALUE).set(true);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
ServerReload.executeReloadAndWaitForCompletion(managementClient);
}
}
@ArquillianResource
private URI uri;
@Deployment
public static Archive<?> dependent() {
return ShrinkWrap.create(WebArchive.class, "stats.war")
.addClasses(SessionTestServlet.class)
.addAsWebInfResource(new StringAsset("<jboss-web><max-active-sessions>" + MAX_SESSIONS + "</max-active-sessions></jboss-web>"), "jboss-web.xml");
}
@Test
public void testSessionManagementOperations() throws Exception {
CloseableHttpClient[] clients = new CloseableHttpClient[CLIENT_COUNT];
try {
for (int i = 0; i < CLIENT_COUNT; ++i) {
clients[i] = HttpClients.createDefault();
}
ModelNode operation = new ModelNode();
operation.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION);
operation.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true);
operation.get(ModelDescriptionConstants.OP_ADDR).set(PathAddress.parseCLIStyleAddress("/deployment=stats.war/subsystem=undertow").toModelNode());
ModelNode opRes = managementClient.getControllerClient().execute(operation);
Assert.assertEquals(opRes.toString(), "success", opRes.get(ModelDescriptionConstants.OUTCOME).asString());
ModelNode result = opRes.get(ModelDescriptionConstants.RESULT);
//check everything is zero
Assert.assertEquals(0, result.get(ACTIVE_SESSIONS).asInt());
Assert.assertEquals(0, result.get(EXPIRED_SESSIONS).asInt());
Assert.assertEquals(0, result.get(HIGHEST_SESSION_COUNT).asInt());
Assert.assertEquals(4, result.get(MAX_ACTIVE_SESSIONS).asInt());
Assert.assertEquals(0, result.get(REJECTED_SESSIONS).asInt());
Assert.assertEquals(0, result.get("session-avg-alive-time").asInt());
Assert.assertEquals(0, result.get("session-max-alive-time").asInt());
Assert.assertEquals(0, result.get(SESSIONS_CREATED).asInt());
final HttpGet get = new HttpGet(uri.toString() + "/SessionPersistenceServlet");
final HttpGet invalidate = new HttpGet(get.getURI().toString() + "?invalidate=true");
HttpResponse res = clients[0].execute(get);
Assert.assertEquals(StatusCodes.OK, res.getStatusLine().getStatusCode());
EntityUtils.consume(res.getEntity());
opRes = managementClient.getControllerClient().execute(operation);
Assert.assertEquals(opRes.toString(), "success", opRes.get(ModelDescriptionConstants.OUTCOME).asString());
result = opRes.get(ModelDescriptionConstants.RESULT);
//create a session and check that it worked
Assert.assertEquals(1, result.get(ACTIVE_SESSIONS).asInt());
Assert.assertEquals(0, result.get(EXPIRED_SESSIONS).asInt());
Assert.assertEquals(1, result.get(HIGHEST_SESSION_COUNT).asInt());
Assert.assertEquals(MAX_SESSIONS, result.get(MAX_ACTIVE_SESSIONS).asInt());
Assert.assertEquals(0, result.get(REJECTED_SESSIONS).asInt());
Assert.assertEquals(1, result.get(SESSIONS_CREATED).asInt());
//this should use the same session
res = clients[0].execute(get);
Assert.assertEquals(StatusCodes.OK, res.getStatusLine().getStatusCode());
EntityUtils.consume(res.getEntity());
opRes = managementClient.getControllerClient().execute(operation);
Assert.assertEquals(opRes.toString(), "success", opRes.get(ModelDescriptionConstants.OUTCOME).asString());
result = opRes.get(ModelDescriptionConstants.RESULT);
Assert.assertEquals(1, result.get(ACTIVE_SESSIONS).asInt());
Assert.assertEquals(0, result.get(EXPIRED_SESSIONS).asInt());
Assert.assertEquals(1, result.get(HIGHEST_SESSION_COUNT).asInt());
Assert.assertEquals(MAX_SESSIONS, result.get(MAX_ACTIVE_SESSIONS).asInt());
Assert.assertEquals(0, result.get(REJECTED_SESSIONS).asInt());
Assert.assertEquals(1, result.get(SESSIONS_CREATED).asInt());
res = clients[0].execute(invalidate);
Assert.assertEquals(StatusCodes.OK, res.getStatusLine().getStatusCode());
EntityUtils.consume(res.getEntity());
opRes = managementClient.getControllerClient().execute(operation);
Assert.assertEquals(opRes.toString(), "success", opRes.get(ModelDescriptionConstants.OUTCOME).asString());
result = opRes.get(ModelDescriptionConstants.RESULT);
Assert.assertEquals(0, result.get(ACTIVE_SESSIONS).asInt());
Assert.assertEquals(1, result.get(EXPIRED_SESSIONS).asInt());
Assert.assertEquals(1, result.get(HIGHEST_SESSION_COUNT).asInt());
Assert.assertEquals(MAX_SESSIONS, result.get(MAX_ACTIVE_SESSIONS).asInt());
Assert.assertEquals(0, result.get(REJECTED_SESSIONS).asInt());
Assert.assertEquals(1, result.get(SESSIONS_CREATED).asInt());
for (int i = 0; i < CLIENT_COUNT; ++i) {
res = clients[i].execute(get);
Assert.assertEquals(i >= MAX_SESSIONS ? StatusCodes.INTERNAL_SERVER_ERROR : StatusCodes.OK, res.getStatusLine().getStatusCode());
EntityUtils.consume(res.getEntity());
}
opRes = managementClient.getControllerClient().execute(operation);
Assert.assertEquals(opRes.toString(), "success", opRes.get(ModelDescriptionConstants.OUTCOME).asString());
result = opRes.get(ModelDescriptionConstants.RESULT);
Assert.assertEquals(MAX_SESSIONS, result.get(ACTIVE_SESSIONS).asInt());
Assert.assertEquals(1, result.get(EXPIRED_SESSIONS).asInt());
Assert.assertEquals(MAX_SESSIONS, result.get(HIGHEST_SESSION_COUNT).asInt());
Assert.assertEquals(MAX_SESSIONS, result.get(MAX_ACTIVE_SESSIONS).asInt());
Assert.assertEquals(CLIENT_COUNT - MAX_SESSIONS, result.get(REJECTED_SESSIONS).asInt());
Assert.assertEquals(MAX_SESSIONS + 1, result.get(SESSIONS_CREATED).asInt());
for (int i = 0; i < MAX_SESSIONS; ++i) {
res = clients[i].execute(invalidate);
Assert.assertEquals(StatusCodes.OK, res.getStatusLine().getStatusCode());
EntityUtils.consume(res.getEntity());
}
opRes = managementClient.getControllerClient().execute(operation);
Assert.assertEquals(opRes.toString(), "success", opRes.get(ModelDescriptionConstants.OUTCOME).asString());
result = opRes.get(ModelDescriptionConstants.RESULT);
Assert.assertEquals(0, result.get(ACTIVE_SESSIONS).asInt());
Assert.assertEquals(MAX_SESSIONS + 1, result.get(EXPIRED_SESSIONS).asInt());
Assert.assertEquals(MAX_SESSIONS, result.get(HIGHEST_SESSION_COUNT).asInt());
Assert.assertEquals(MAX_SESSIONS, result.get(MAX_ACTIVE_SESSIONS).asInt());
Assert.assertEquals(CLIENT_COUNT - MAX_SESSIONS, result.get(REJECTED_SESSIONS).asInt());
Assert.assertEquals(MAX_SESSIONS + 1, result.get(SESSIONS_CREATED).asInt());
} finally {
for (CloseableHttpClient i : clients) {
IoUtils.safeClose(i);
}
}
}
}
| 11,621
| 52.557604
| 161
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/session/ObfuscatedRouteSessionManagementTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 2110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.session;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.dmr.ModelNode;
import static org.jboss.as.controller.client.helpers.ClientConstants.FAILURE_DESCRIPTION;
import static org.jboss.as.controller.client.helpers.ClientConstants.OUTCOME;
import static org.jboss.as.controller.client.helpers.ClientConstants.SUCCESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import org.junit.runner.RunWith;
/**
* Runs {@link SessionManagementTestCase} with Undertow subsystem {@code obfuscate-session-route} attribute set to
* {@code true}.
*
* @author Flavia Rainone
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(ObfuscatedRouteSessionManagementTestCase.SetupTask.class)
public class ObfuscatedRouteSessionManagementTestCase extends SessionManagementTestCase {
static class SetupTask implements ServerSetupTask {
private static Exception failure;
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
failure = null;
try {
final ModelNode op = Util.getWriteAttributeOperation(
PathAddress.pathAddress(SUBSYSTEM, "undertow"),
"obfuscate-session-route", true);
runOperationAndReload(op, managementClient);
} catch (Exception e) {
failure = e;
throw e;
}
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
if (failure != null)
return;
try {
final ModelNode op = Util.getWriteAttributeOperation(
PathAddress.pathAddress(SUBSYSTEM, "undertow"),
"obfuscate-session-route", false);
runOperationAndReload(op, managementClient);
} catch (Exception e) {
failure = e;
throw e;
}
}
private void runOperationAndReload(ModelNode operation, ManagementClient client) throws Exception {
final ModelNode result = client.getControllerClient().execute(operation);
if (result.hasDefined(FAILURE_DESCRIPTION)) {
final String failureDesc = result.get(FAILURE_DESCRIPTION).toString();
throw new RuntimeException(failureDesc);
}
if (!result.hasDefined(OUTCOME) || !SUCCESS.equals(result.get(OUTCOME).asString())) {
throw new RuntimeException("Operation not successful; outcome = " + result.get(OUTCOME));
}
ServerReload.reloadIfRequired(client);
}
public static Exception getFailure() {
return failure;
}
}
}
| 4,252
| 41.108911
| 114
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/session/SessionManagementTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 2110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.session;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
*/
@RunWith(Arquillian.class)
@RunAsClient
public class SessionManagementTestCase {
private static final String SESSION_ID = "session-id";
private static final String ATTRIBUTE = "attribute";
private static final String INVALIDATE_SESSION = "invalidate-session";
private static final String LIST_SESSIONS = "list-sessions";
private static final String LIST_SESSION_ATTRIBUTE_NAMES = "list-session-attribute-names";
private static final String LIST_SESSION_ATTRIBUTES = "list-session-attributes";
private static final String GET_SESSION_ATTRIBUTE = "get-session-attribute";
private static final String GET_SESSION_LAST_ACCESSED_TIME = "get-session-last-accessed-time";
private static final String GET_SESSION_LAST_ACCESSED_TIME_MILLIS = "get-session-last-accessed-time-millis";
private static final String GET_SESSION_CREATION_TIME = "get-session-creation-time";
private static final String GET_SESSION_CREATION_TIME_MILLIS = "get-session-creation-time-millis";
@ArquillianResource
public ManagementClient managementClient;
@Deployment
public static Archive<?> dependent() {
return ShrinkWrap.create(WebArchive.class, "management.war")
.addClasses(SessionTestServlet.class);
}
@Test
public void testSessionManagementOperations() throws Exception {
try (CloseableHttpClient client = HttpClients.createDefault()) {
ModelNode operation = new ModelNode();
operation.get(ModelDescriptionConstants.OP).set(LIST_SESSIONS);
operation.get(ModelDescriptionConstants.OP_ADDR).set(PathAddress.parseCLIStyleAddress("/deployment=management.war/subsystem=undertow").toModelNode());
ModelNode opRes = managementClient.getControllerClient().execute(operation);
Assert.assertEquals(opRes.toString(), "success", opRes.get(ModelDescriptionConstants.OUTCOME).asString());
Assert.assertEquals(Collections.emptyList(), opRes.get(ModelDescriptionConstants.RESULT).asList());
long c1 = System.currentTimeMillis();
HttpGet get = new HttpGet("http://" + TestSuiteEnvironment.getServerAddress() + ":8080/management/SessionPersistenceServlet");
HttpResponse res = client.execute(get);
long c2 = System.currentTimeMillis();
String sessionId = null;
for (Header cookie : res.getHeaders("Set-Cookie")) {
if (cookie.getValue().startsWith("JSESSIONID=")) {
sessionId = cookie.getValue().split("=")[1].split("\\.")[0];
break;
}
}
Assert.assertNotNull(sessionId);
opRes = managementClient.getControllerClient().execute(operation);
Assert.assertEquals(opRes.toString(), "success", opRes.get(ModelDescriptionConstants.OUTCOME).asString());
Assert.assertEquals(opRes.toString(), Collections.singletonList(new ModelNode(sessionId)), opRes.get(ModelDescriptionConstants.RESULT).asList());
operation.get(SESSION_ID).set(sessionId);
opRes = executeOperation(operation, GET_SESSION_CREATION_TIME_MILLIS);
long time1 = opRes.get(ModelDescriptionConstants.RESULT).asLong();
Assert.assertTrue(c1 <= time1);
Assert.assertTrue(time1 <= c2);
opRes = executeOperation(operation, GET_SESSION_CREATION_TIME);
long sessionCreationTime = LocalDateTime.parse(opRes.get(ModelDescriptionConstants.RESULT).asString(), DateTimeFormatter.ISO_DATE_TIME).toInstant(ZoneId.systemDefault().getRules().getOffset(Instant.now())).toEpochMilli();
Assert.assertEquals(time1, sessionCreationTime);
opRes = executeOperation(operation, GET_SESSION_LAST_ACCESSED_TIME_MILLIS);
Assert.assertEquals(time1, opRes.get(ModelDescriptionConstants.RESULT).asLong());
opRes = executeOperation(operation, GET_SESSION_LAST_ACCESSED_TIME);
long aTime2 = LocalDateTime.parse(opRes.get(ModelDescriptionConstants.RESULT).asString(), DateTimeFormatter.ISO_DATE_TIME).toInstant(ZoneId.systemDefault().getRules().getOffset(Instant.now())).toEpochMilli();
Assert.assertEquals(time1, aTime2);
Assert.assertEquals(sessionCreationTime, aTime2);
opRes = executeOperation(operation, LIST_SESSION_ATTRIBUTE_NAMES);
List<ModelNode> resultList = opRes.get(ModelDescriptionConstants.RESULT).asList();
Assert.assertEquals(1, resultList.size());
Assert.assertEquals(opRes.toString(), "val", resultList.get(0).asString());
opRes = executeOperation(operation, LIST_SESSION_ATTRIBUTES);
List<Property> properties = opRes.get(ModelDescriptionConstants.RESULT).asPropertyList();
Assert.assertEquals(opRes.toString(), 1, properties.size());
Property property = properties.get(0);
Assert.assertEquals(opRes.toString(), "val", property.getName());
Assert.assertEquals(opRes.toString(), "0", property.getValue().asString());
//we want to make sure that the values will be different
//so we wait 10ms
Thread.sleep(10);
long a1 = System.currentTimeMillis();
client.execute(get);
long a2 = System.currentTimeMillis();
do {
//because the last access time is updated after the request returns there is a possible race here
//to get around this we execute this op in a loop and wait for the value to change
//in 99% of cases this will only iterate once
//because of the 10ms sleep above they should ways be different
//we have a max wait time of 1s if something goes wrong
opRes = executeOperation(operation, GET_SESSION_LAST_ACCESSED_TIME_MILLIS);
time1 = opRes.get(ModelDescriptionConstants.RESULT).asLong();
if(time1 != sessionCreationTime) {
break;
}
} while (System.currentTimeMillis() < a1 + 1000);
Assert.assertTrue(a1 <= time1);
Assert.assertTrue(time1 <= a2);
opRes = executeOperation(operation, GET_SESSION_LAST_ACCESSED_TIME);
long time2 = LocalDateTime.parse(opRes.get(ModelDescriptionConstants.RESULT).asString(), DateTimeFormatter.ISO_DATE_TIME).toInstant(ZoneId.systemDefault().getRules().getOffset(Instant.now())).toEpochMilli();
Assert.assertEquals(time1, time2);
operation.get(ATTRIBUTE).set("val");
opRes = executeOperation(operation, GET_SESSION_ATTRIBUTE);
Assert.assertEquals("1", opRes.get(ModelDescriptionConstants.RESULT).asString());
executeOperation(operation, INVALIDATE_SESSION);
opRes = executeOperation(operation, LIST_SESSIONS);
Assert.assertEquals(Collections.emptyList(), opRes.get(ModelDescriptionConstants.RESULT).asList());
}
}
@Test
public void testSessionManagementOperationsNegative() throws Exception {
try (CloseableHttpClient client = HttpClients.createDefault()) {
ModelNode operation = new ModelNode();
operation.get(ModelDescriptionConstants.OP_ADDR).set(PathAddress.parseCLIStyleAddress
("/deployment=management.war/subsystem=undertow").toModelNode());
String sessionId = "non-existing-id";
operation.get(SESSION_ID).set(sessionId);
negativeTestsCheck(operation, LIST_SESSION_ATTRIBUTE_NAMES);
negativeTestsCheck(operation, LIST_SESSION_ATTRIBUTES);
operation.get(ATTRIBUTE).set("val");
negativeTestsCheck(operation, GET_SESSION_ATTRIBUTE);
executeOperation(operation, INVALIDATE_SESSION);
HttpGet get = new HttpGet("http://" + TestSuiteEnvironment.getServerAddress() +
":8080/management/SessionPersistenceServlet");
HttpResponse res = client.execute(get);
sessionId = null;
for (Header cookie : res.getHeaders("Set-Cookie")) {
if (cookie.getValue().startsWith("JSESSIONID=")) {
sessionId = cookie.getValue().split("=")[1].split("\\.")[0];
break;
}
}
operation.get(SESSION_ID).set(sessionId);
operation.get(ATTRIBUTE).set("non-existing");
ModelNode opRes = executeOperation(operation, GET_SESSION_ATTRIBUTE);
Assert.assertEquals("undefined", opRes.get(ModelDescriptionConstants.RESULT).asString());
// Invalidate created session.
executeOperation(operation, INVALIDATE_SESSION);
}
}
private ModelNode executeOperation(ModelNode operation, String operationName) throws IOException {
operation.get(ModelDescriptionConstants.OP).set(operationName);
ModelNode opRes = managementClient.getControllerClient().execute(operation);
Assert.assertEquals(opRes.toString(), "success", opRes.get(ModelDescriptionConstants.OUTCOME).asString());
return opRes;
}
private void negativeTestsCheck(ModelNode operation, String operationName) throws IOException {
operation.get(ModelDescriptionConstants.OP).set(operationName);
ModelNode opRes = managementClient.getControllerClient().execute(operation);
Assert.assertEquals(opRes.toString(), "failed", opRes.get(ModelDescriptionConstants.OUTCOME).asString());
String failDesc = opRes.get(ModelDescriptionConstants.FAILURE_DESCRIPTION).asString();
Assert.assertTrue(failDesc.contains("WFLYUT0100"));
}
}
| 11,966
| 50.360515
| 233
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlestypes/ChildServletContainerInitializer.java
|
package org.jboss.as.test.integration.web.handlestypes;
import jakarta.servlet.ServletContainerInitializer;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HandlesTypes;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* @author Stuart Douglas
*/
@HandlesTypes({HandlesTypesChild.class, HandlesTypesImplementor.class})
public class ChildServletContainerInitializer implements ServletContainerInitializer {
public static final Set<Class<?>> HANDLES_TYPES = new CopyOnWriteArraySet<>();
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
HANDLES_TYPES.addAll(c);
}
}
| 731
| 30.826087
| 88
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlestypes/HandlesTypesGandchild.java
|
package org.jboss.as.test.integration.web.handlestypes;
/**
* @author Stuart Douglas
*/
public class HandlesTypesGandchild extends HandlesTypesChild {
}
| 156
| 18.625
| 62
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlestypes/AnnotatedChild.java
|
package org.jboss.as.test.integration.web.handlestypes;
/**
* @author Stuart Douglas
*/
@SomeAnnotation
public class AnnotatedChild extends AnnotatedParent {
}
| 163
| 17.222222
| 55
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlestypes/HandlesTypesImplementorChild.java
|
package org.jboss.as.test.integration.web.handlestypes;
/**
* @author Stuart Douglas
*/
public class HandlesTypesImplementorChild extends HandlesTypesImplementor {
}
| 169
| 20.25
| 75
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlestypes/HandlesTypesEarTestCase.java
|
package org.jboss.as.test.integration.web.handlestypes;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import jakarta.servlet.ServletContainerInitializer;
import java.util.Arrays;
import java.util.HashSet;
/**
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
public class HandlesTypesEarTestCase {
@Deployment
public static Archive<?> deploy() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "test.war")
.addClasses(SomeAnnotation.class, HandlesTypesEarTestCase.class)
.addClasses(NonAnnotatedChild.class, AnnotatedChild.class)
.addClasses(HandlesTypesChild.class, HandlesTypesGandchild.class)
.addClasses(HandlesTypesImplementor.class, HandlesTypesImplementorChild.class)
.addClasses(ParentServletContainerInitializer.class, ChildServletContainerInitializer.class, AnnotationServletContainerInitializer.class)
.addAsServiceProvider(ServletContainerInitializer.class, ParentServletContainerInitializer.class, ChildServletContainerInitializer.class, AnnotationServletContainerInitializer.class);
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "lib.jar")
.addClasses(AnnotatedParent.class, HandlesTypesInterface.class, HandlesTypesParent.class);
EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "sci.ear")
.addAsLibrary(jar)
.addAsModule(war);
return ear;
}
@Test
public void testParentClass() {
Class<?>[] expeccted = {HandlesTypesChild.class, HandlesTypesImplementor.class, HandlesTypesGandchild.class, HandlesTypesImplementorChild.class};
Assert.assertEquals(new HashSet<>(Arrays.asList(expeccted)), ParentServletContainerInitializer.HANDLES_TYPES);
}
@Test
public void testChildClass() {
Class<?>[] expeccted = {HandlesTypesGandchild.class, HandlesTypesImplementorChild.class};
Assert.assertEquals(new HashSet<>(Arrays.asList(expeccted)), ChildServletContainerInitializer.HANDLES_TYPES);
}
@Test
public void testAnnotatedClass() {
Class<?>[] expeccted = {AnnotatedParent.class, AnnotatedChild.class};
Assert.assertEquals(new HashSet<>(Arrays.asList(expeccted)), AnnotationServletContainerInitializer.HANDLES_TYPES);
}
}
| 2,725
| 42.269841
| 199
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlestypes/HandlesTypesParent.java
|
package org.jboss.as.test.integration.web.handlestypes;
/**
* @author Stuart Douglas
*/
public class HandlesTypesParent {
}
| 127
| 15
| 55
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlestypes/HandlesTypesImplementor.java
|
package org.jboss.as.test.integration.web.handlestypes;
/**
* @author Stuart Douglas
*/
public class HandlesTypesImplementor implements HandlesTypesInterface {
}
| 165
| 19.75
| 71
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlestypes/HandlesTypesChild.java
|
package org.jboss.as.test.integration.web.handlestypes;
/**
* @author Stuart Douglas
*/
public class HandlesTypesChild extends HandlesTypesParent {
}
| 153
| 18.25
| 59
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlestypes/SomeAnnotation.java
|
package org.jboss.as.test.integration.web.handlestypes;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* @author Stuart Douglas
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface SomeAnnotation {
}
| 249
| 19.833333
| 55
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlestypes/AnnotatedParent.java
|
package org.jboss.as.test.integration.web.handlestypes;
/**
* @author Stuart Douglas
*/
@SomeAnnotation
public class AnnotatedParent {
}
| 140
| 14.666667
| 55
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlestypes/HandlesTypesInterface.java
|
package org.jboss.as.test.integration.web.handlestypes;
/**
* @author Stuart Douglas
*/
public interface HandlesTypesInterface {
}
| 134
| 15.875
| 55
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlestypes/NonAnnotatedChild.java
|
package org.jboss.as.test.integration.web.handlestypes;
/**
* @author Stuart Douglas
*/
public class NonAnnotatedChild extends AnnotatedParent {
}
| 150
| 17.875
| 56
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlestypes/AnnotationServletContainerInitializer.java
|
package org.jboss.as.test.integration.web.handlestypes;
import jakarta.servlet.ServletContainerInitializer;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HandlesTypes;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* @author Stuart Douglas
*/
@HandlesTypes({SomeAnnotation.class})
public class AnnotationServletContainerInitializer implements ServletContainerInitializer {
public static final Set<Class<?>> HANDLES_TYPES = new CopyOnWriteArraySet<>();
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
HANDLES_TYPES.addAll(c);
}
}
| 702
| 29.565217
| 91
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlestypes/ParentServletContainerInitializer.java
|
package org.jboss.as.test.integration.web.handlestypes;
import jakarta.servlet.ServletContainerInitializer;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HandlesTypes;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* @author Stuart Douglas
*/
@HandlesTypes({HandlesTypesParent.class, HandlesTypesInterface.class})
public class ParentServletContainerInitializer implements ServletContainerInitializer {
public static final Set<Class<?>> HANDLES_TYPES = new CopyOnWriteArraySet<>();
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
HANDLES_TYPES.addAll(c);
}
}
| 731
| 30.826087
| 88
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.