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/elytron/src/test/java/org/wildfly/test/integration/elytron/jaspi/ConfiguredAdHocJaspiTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.jaspi;
import java.util.HashMap;
import java.util.Map;
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.shared.categories.RequiresTransformedClass;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
/**
* Test case testing a deployment secured using JASPI configured within the Elytron subsystem with the authentication being
* handled by the ServerAuthModule and an AdHoc identity being created.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ ConfiguredAdHocJaspiTestCase.ServerSetup.class })
@Category(RequiresTransformedClass.class)
public class ConfiguredAdHocJaspiTestCase extends ConfiguredJaspiTestBase {
private static final String NAME = ConfiguredAdHocJaspiTestCase.class.getSimpleName();
@Deployment(testable = false)
public static WebArchive createDeployment() {
return createDeployment(NAME);
}
static class ServerSetup extends ConfiguredJaspiTestBase.ServerSetup {
@Override
protected String getName() {
return NAME;
}
@Override
protected String getMode() {
// We still want self-validating as ad-hoc does not support PasswordValidationCallback
return "self-validating";
}
@Override
protected Map<String, String> getOptions() {
Map<String, String> options = new HashMap<>();
options.putAll(super.getOptions());
options.put("default-roles", "Role1");
return options;
}
@Override
protected boolean isIntegratedJaspi() {
return false;
}
}
}
| 3,023
| 33.758621
| 123
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/jaspi/ConfiguredJaspiTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.jaspi;
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.shared.categories.RequiresTransformedClass;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
/**
* Test case testing a deployment secured using JASPI configured within the Elytron subsystem with the actual authentication
* handled by the mapped SecurityDomain of the deployment.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ ConfiguredJaspiTestCase.ServerSetup.class })
@Category(RequiresTransformedClass.class)
public class ConfiguredJaspiTestCase extends ConfiguredJaspiTestBase {
private static final String NAME = ConfiguredJaspiTestCase.class.getSimpleName();
@Deployment(testable = false)
public static WebArchive createDeployment() {
return createDeployment(NAME);
}
static class ServerSetup extends ConfiguredJaspiTestBase.ServerSetup {
@Override
protected String getName() {
return NAME;
}
@Override
protected boolean enableAnonymousLogin() {
return true;
}
}
}
| 2,475
| 35.955224
| 124
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/jaspi/JaspiConfiguration.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.jaspi;
import static org.wildfly.test.security.common.ModelNodeUtil.setIfNotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.management.util.CLIWrapper;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.dmr.ModelNode;
import org.wildfly.security.auth.jaspi.Flag;
import org.wildfly.test.security.common.elytron.AbstractConfigurableElement;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
/**
* A {@link ConfigurableElement} to add a jaspi-configuration resource.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
class JaspiConfiguration extends AbstractConfigurableElement {
/*
* Reduced visibility until we decide to make this accessible for use elsewhere which would also mean moving this class into
* common.
*/
private final PathAddress address;
private final String layer;
private final String applicationContext;
private final String description;
private final List<ModuleDefinition> modules;
private JaspiConfiguration(Builder builder) {
super(builder);
this.address = PathAddress.pathAddress().append("subsystem", "elytron").append("jaspi-configuration", name);
this.layer = builder.layer;
this.applicationContext = builder.applicationContext;
this.description = builder.description;
this.modules = builder.modules;
}
@Override
public void create(ModelControllerClient client, CLIWrapper cli) throws Exception {
ModelNode add = Util.createAddOperation(address);
setIfNotNull(add, "layer", layer);
setIfNotNull(add, "application-context", applicationContext);
setIfNotNull(add, "description", description);
ModelNode modules = add.get("server-auth-modules");
for (ModuleDefinition moduleDefinition : this.modules) {
ModelNode module = new ModelNode();
setIfNotNull(module, "class-name", moduleDefinition.className);
setIfNotNull(module, "module", moduleDefinition.module);
setIfNotNull(module, "flag", moduleDefinition.flag.toString());
if (moduleDefinition.options != null) {
ModelNode options = module.get("options");
for (Entry<String, String> entry : moduleDefinition.options.entrySet()) {
options.get(entry.getKey()).set(entry.getValue());
}
}
modules.add(module);
}
Utils.applyUpdate(add, client);
}
@Override
public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception {
Utils.applyUpdate(Util.createRemoveOperation(address), client);
}
/**
* Creates a new {@link Builder} to configure a jaspi-configuration resource.
*
* @return a new {@link Builder} to configure a jaspi-configuration resource.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder to build an jaspi-configuration resource in the Elytron subsystem
*/
public static final class Builder extends AbstractConfigurableElement.Builder<Builder> {
private String layer;
private String applicationContext;
private String description;
private List<ModuleDefinition> modules = new ArrayList<>();
/**
* Set the layer to be specified in this jaspi-configuration.
*
* @param layer the layer to be specified in this jaspi.configuration.
* @return this {@link Builder} to allow method chaining.
*/
public Builder withLayer(final String layer) {
this.layer = layer;
return this;
}
/**
* Set the application-context to be specified in this jaspi-configuration.
*
* @param applicationContext the application-context to be specified in this jaspi-configuration.
* @return this {@link Builder} to allow method chaining.
*/
public Builder withApplicationContext(final String applicationContext) {
this.applicationContext = applicationContext;
return this;
}
/**
* Set the description to be associated with this jaspi-configuration.
*
* @param description the description to be associated with this jaspi-configuration.
* @return this {@link Builder} to allow method chaining.
*/
public Builder withDescription(final String description) {
this.description = description;
return this;
}
/**
* Add a server-auth-module definition for this jaspi-configuration resource.
*
* @param className the fully qualified class name of the ServerAuthModule
* @param module the name of the module containing the ServerAuthModule or {@code null}
* @param flag the control flag for the ServerAuthModule or {@code null}
* @param options configuration options to be passed to the ServerAuthModule} or {@code null}
* @return this {@link Builder} to allow method chaining.
*/
public Builder withServerAuthModule(final String className, final String module, final Flag flag, final Map<String, String> options) {
modules.add(new ModuleDefinition(className, module, flag, options));
return this;
}
/**
* Build an instance of {@link JaspiConfiguration}
*
* @return an instance of {@link JaspiConfiguration}
*/
public JaspiConfiguration build() {
return new JaspiConfiguration(this);
}
@Override
protected Builder self() {
return this;
}
}
static class ModuleDefinition {
final String className;
final String module;
final Flag flag;
final Map<String, String> options;
ModuleDefinition(final String className, final String module, final Flag flag, final Map<String, String> options) {
this.className = className;
this.module = module;
this.flag = flag;
this.options = options;
}
}
}
| 7,455
| 36.094527
| 141
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/jaspi/ConfiguredJaspiTestBase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.jaspi;
import static org.apache.http.HttpStatus.SC_FORBIDDEN;
import static org.apache.http.HttpStatus.SC_OK;
import static org.apache.http.HttpStatus.SC_UNAUTHORIZED;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.wildfly.test.integration.elytron.jaspi.SimpleServerAuthModule.ANONYMOUS;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
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.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.management.util.CLIWrapper;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assume;
import org.junit.Test;
import org.wildfly.security.auth.jaspi.Flag;
import org.wildfly.test.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
import org.wildfly.test.security.common.elytron.Module;
import org.wildfly.test.undertow.common.UndertowApplicationSecurityDomain;
/**
* A base for the configured JASPI testing allowing us to repeat the same set of tests across a different set of server
* configurations.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
abstract class ConfiguredJaspiTestBase extends JaspiTestBase {
private static final String MODULE_NAME = "org.wildfly.security.examples.jaspi";
@Test
public void testAnonymous() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm()));
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// Verify that we are challenged.
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
Header[] challenge = response.getHeaders("X-MESSAGE");
assertEquals("Only 1 header expected", 1, challenge.length);
assertTrue("Challenge information contained in header.", challenge[0].getValue().contains("X-USERNAME"));
assertTrue("Challenge information contained in header.", challenge[0].getValue().contains("X-PASSWORD"));
}
// Now authenticate.
request.addHeader("X-USERNAME", ANONYMOUS);
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "null", EntityUtils.toString(response.getEntity()));
}
}
}
@Test
public void testSuccess() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1"));
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// Verify that we are challenged.
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
Header[] challenge = response.getHeaders("X-MESSAGE");
assertEquals("Only 1 header expected", 1, challenge.length);
assertTrue("Challenge information contained in header.", challenge[0].getValue().contains("X-USERNAME"));
assertTrue("Challenge information contained in header.", challenge[0].getValue().contains("X-PASSWORD"));
}
// Now authenticate.
request.addHeader("X-USERNAME", "user1");
request.addHeader("X-PASSWORD", "password1");
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "user1", EntityUtils.toString(response.getEntity()));
}
request = new HttpGet(new URI(url.toExternalForm() + "role1?value=authType"));
request.addHeader("X-USERNAME", "user1");
request.addHeader("X-PASSWORD", "password1");
request.addHeader("X-AUTH-TYPE", "TestAuth");
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "TestAuth", EntityUtils.toString(response.getEntity()));
}
}
}
@Test
public void testSuccess_Session() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1"));
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// Verify that we are challenged.
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
Header[] challenge = response.getHeaders("X-MESSAGE");
assertEquals("Only 1 header expected", 1, challenge.length);
assertTrue("Challenge information contained in header.", challenge[0].getValue().contains("X-USERNAME"));
assertTrue("Challenge information contained in header.", challenge[0].getValue().contains("X-PASSWORD"));
}
// Now authenticate.
request.addHeader("X-USERNAME", "user1");
request.addHeader("X-PASSWORD", "password1");
request.addHeader("X-AUTH-TYPE", "SessionAuth");
request.addHeader("X-SESSION", "register");
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "user1", EntityUtils.toString(response.getEntity()));
}
// Repeat without headers
request = new HttpGet(new URI(url.toExternalForm() + "role1"));
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "user1", EntityUtils.toString(response.getEntity()));
}
// Was the authType saved?
request = new HttpGet(new URI(url.toExternalForm() + "role1?value=authType"));
request.addHeader("X-AUTH-TYPE", "SessionAuth");
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "SessionAuth", EntityUtils.toString(response.getEntity()));
}
}
}
@Test
public void testSuccess_EJB() throws Exception {
Assume.assumeTrue("EJB is not supported on the server; disabling ejb test aspects", ejbSupported);
final HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1?action=ejb"));
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// Verify that we are challenged.
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
Header[] challenge = response.getHeaders("X-MESSAGE");
assertEquals("Only 1 header expected", 1, challenge.length);
assertTrue("Challenge information contained in header.", challenge[0].getValue().contains("X-USERNAME"));
assertTrue("Challenge information contained in header.", challenge[0].getValue().contains("X-PASSWORD"));
}
// Now authenticate.
request.addHeader("X-USERNAME", "user1");
request.addHeader("X-PASSWORD", "password1");
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "user1", EntityUtils.toString(response.getEntity()));
}
}
}
@Test
public void testInsufficientRole() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role2"));
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// Verify that we are challenged.
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
Header[] challenge = response.getHeaders("X-MESSAGE");
assertEquals("Only 1 header expected", 1, challenge.length);
assertTrue("Challenge information contained in header.", challenge[0].getValue().contains("X-USERNAME"));
assertTrue("Challenge information contained in header.", challenge[0].getValue().contains("X-PASSWORD"));
}
// Now authenticate.
request.addHeader("X-USERNAME", "user1");
request.addHeader("X-PASSWORD", "password1");
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_FORBIDDEN, statusCode);
}
// Now try adding the role.
request.addHeader("X-ROLES", "Role1,Role2");
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "user1", EntityUtils.toString(response.getEntity()));
}
}
}
@Test
public void testInvalidPrincipal() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1"));
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// Verify that we are challenged.
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
Header[] challenge = response.getHeaders("X-MESSAGE");
assertEquals("Only 1 header expected", 1, challenge.length);
assertTrue("Challenge information contained in header.", challenge[0].getValue().contains("X-USERNAME"));
assertTrue("Challenge information contained in header.", challenge[0].getValue().contains("X-PASSWORD"));
}
// Now authenticate.
request.addHeader("X-USERNAME", "user1wrong");
request.addHeader("X-PASSWORD", "password1");
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
}
}
}
@Test
public void testInvalidCredential() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1"));
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// Verify that we are challenged.
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
Header[] challenge = response.getHeaders("X-MESSAGE");
assertEquals("Only 1 header expected", 1, challenge.length);
assertTrue("Challenge information contained in header.", challenge[0].getValue().contains("X-USERNAME"));
assertTrue("Challenge information contained in header.", challenge[0].getValue().contains("X-PASSWORD"));
}
// Now authenticate.
request.addHeader("X-USERNAME", "user1");
request.addHeader("X-PASSWORD", "password1wrong");
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
}
}
}
abstract static class ServerSetup extends AbstractElytronSetupTask {
private Path modulePath = null;
@Override
protected void setup(ModelControllerClient modelControllerClient) throws Exception {
// Create the module jar.
modulePath = createJar("jaspiSAM", SimpleServerAuthModule.class);
super.setup(modelControllerClient);
}
@Override
protected ConfigurableElement[] getConfigurableElements() {
ConfigurableElement[] elements = new ConfigurableElement[enableAnonymousLogin() ? 4 : 3];
// 1 - Register the module
elements[0] = Module.builder()
.withName(MODULE_NAME)
.withResource(modulePath.toAbsolutePath().toString())
.withDependency("javax.security.auth.message.api")
.withDependency("javax.servlet.api")
.withDependency("org.wildfly.security.elytron")
.build();
// 2 - Map the application-security-domain
elements[1] = UndertowApplicationSecurityDomain.builder()
.withName("JaspiDomain")
.withSecurityDomain("ApplicationDomain")
.withIntegratedJaspi(isIntegratedJaspi())
.build();
// 3 - Add the jaspi-configuration
elements[2] = JaspiConfiguration.builder()
.withName(getName())
.withLayer("HttpServlet")
.withApplicationContext("default-host /" + getName())
.withServerAuthModule("org.wildfly.test.integration.elytron.jaspi.SimpleServerAuthModule", MODULE_NAME, Flag.REQUIRED, getOptions())
.build();
if (enableAnonymousLogin()) {
elements[3] = new ConfigurableElement() {
private final PathAddress ADDRESS = PathAddress.pathAddress(PathElement.pathElement("subsystem", "elytron"), PathElement.pathElement("simple-permission-mapper", "default-permission-mapper"));
@Override
public String getName() {
return "Enable LoginPermission for anonymous.";
}
@Override
public void create(ModelControllerClient client, CLIWrapper cli) throws Exception {
ModelNode write = Util.getWriteAttributeOperation(ADDRESS, "mapping-mode", "or");
Utils.applyUpdate(write, client);
}
@Override
public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception {
ModelNode write = Util.getWriteAttributeOperation(ADDRESS, "mapping-mode", "first");
Utils.applyUpdate(write, client);
}
};
}
return elements;
}
@Override
protected void tearDown(ModelControllerClient modelControllerClient) throws Exception {
super.tearDown(modelControllerClient);
Files.deleteIfExists(modulePath);
}
static Path createJar(String namePrefix, Class<?>... classes) throws IOException {
Path testJar = Files.createTempFile(namePrefix, ".jar");
JavaArchive jar = ShrinkWrap.create(JavaArchive.class).addClasses(classes);
jar.as(ZipExporter.class).exportTo(testJar.toFile(), true);
return testJar;
}
protected abstract String getName();
protected Map<String, String> getOptions() {
return Collections.singletonMap("mode", getMode());
}
protected String getMode() {
return "integrated";
}
protected boolean isIntegratedJaspi() {
return true;
}
protected boolean enableAnonymousLogin() {
return false;
}
}
}
| 19,559
| 48.64467
| 211
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/jaspi/JaspiTestServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.jaspi;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.ejb.EJB;
import jakarta.security.auth.message.config.AuthConfigFactory;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.wildfly.security.auth.jaspi.JaspiConfigurationBuilder;
/**
* A servlet used for JASPI testing.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
public class JaspiTestServlet extends HttpServlet {
private volatile String registrationId;
@EJB
private WhoAmI whoAmIBean;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final PrintWriter writer = resp.getWriter();
final String action = req.getParameter("action");
if (action != null) {
switch (action) {
case "register":
ServletContext servletContext = req.getServletContext();
registrationId = JaspiConfigurationBuilder
.builder("HttpServlet", servletContext.getVirtualServerName() + " " + servletContext.getContextPath())
.addAuthModuleFactory(SimpleServerAuthModule::new)
.register();
writer.print("REGISTERED");
return;
case "remove":
if (registrationId == null) {
throw new IllegalStateException("No registration to remove.");
}
AuthConfigFactory authConfigFactory = AuthConfigFactory.getFactory();
authConfigFactory.removeRegistration(registrationId);
registrationId = null;
writer.print("REMOVED");
return;
case "ejb":
writer.print(String.valueOf(whoAmIBean.getCallerPrincipal()));
return;
}
}
final String value = req.getParameter("value");
if ("authType".equals(value)) {
writer.print(req.getAuthType());
return;
}
writer.print(String.valueOf(req.getUserPrincipal()));
}
}
| 3,446
| 37.730337
| 130
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/jaspi/ConfiguredSelfValidatingJaspiTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.jaspi;
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.shared.categories.RequiresTransformedClass;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.security.auth.server.SecurityDomain;
/**
* Test case testing a deployment secured using JASPI configured within the Elytron subsystem with the authentication being
* handled by the ServerAuthModule but the identity still being loaded from the {@link SecurityDomain}
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ ConfiguredSelfValidatingJaspiTestCase.ServerSetup.class })
@Category(RequiresTransformedClass.class)
public class ConfiguredSelfValidatingJaspiTestCase extends ConfiguredJaspiTestBase {
private static final String NAME = ConfiguredSelfValidatingJaspiTestCase.class.getSimpleName();
@Deployment(testable = false)
public static WebArchive createDeployment() {
return createDeployment(NAME);
}
static class ServerSetup extends ConfiguredJaspiTestBase.ServerSetup {
@Override
protected String getName() {
return NAME;
}
@Override
protected String getMode() {
return "self-validating";
}
@Override
protected boolean enableAnonymousLogin() {
return true;
}
}
}
| 2,721
| 35.783784
| 123
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/jaspi/DynamicJaspiTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.jaspi;
import static org.apache.http.HttpStatus.SC_OK;
import static org.apache.http.HttpStatus.SC_UNAUTHORIZED;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.net.URL;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
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.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.test.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
import org.wildfly.test.undertow.common.UndertowApplicationSecurityDomain;
/**
* Test case testing a deployment secured using JASPI dynamically registered by the deployment.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ DynamicJaspiTestCase.ServerSetup.class })
public class DynamicJaspiTestCase extends JaspiTestBase {
private static final String NAME = ConfiguredJaspiTestCase.class.getSimpleName();
@ArquillianResource
protected URL url;
@Deployment
protected static WebArchive createDeployment() {
return createDeployment(NAME);
}
@Test
public void testCalls() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm()));
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// Verify that we are not challenged.
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "null", EntityUtils.toString(response.getEntity()));
}
// Register JASPI Configuration
request = new HttpGet(new URI(url.toExternalForm()) + "?action=register");
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
Header[] challenge = response.getHeaders("X-MESSAGE");
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("No challenge headers expected", 0, challenge.length);
assertEquals("Unexpected content of HTTP response.", "REGISTERED", EntityUtils.toString(response.getEntity()));
}
// Verify that we are now challenged.
request = new HttpGet(new URI(url.toExternalForm()));
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
Header[] challenge = response.getHeaders("X-MESSAGE");
assertEquals("Only 1 header expected", 1, challenge.length);
assertTrue("Challenge information contained in header.", challenge[0].getValue().contains("X-USERNAME"));
assertTrue("Challenge information contained in header.", challenge[0].getValue().contains("X-PASSWORD"));
}
// Now authenticate.
request.addHeader("X-USERNAME", "user1");
request.addHeader("X-PASSWORD", "password1");
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "user1", EntityUtils.toString(response.getEntity()));
}
if (ejbSupported) {
// Now try and Jakarta Enterprise Beans call
request = new HttpGet(new URI(url.toExternalForm()) + "?action=ejb");
request.addHeader("X-USERNAME", "user1");
request.addHeader("X-PASSWORD", "password1");
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "user1", EntityUtils.toString(response.getEntity()));
}
}
// Remove the registration
request = new HttpGet(new URI(url.toExternalForm()) + "?action=remove");
// Need to be authenticated to make the call.
request.addHeader("X-USERNAME", "user1");
request.addHeader("X-PASSWORD", "password1");
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
Header[] challenge = response.getHeaders("X-MESSAGE");
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("No challenge headers expected", 0, challenge.length);
assertEquals("Unexpected content of HTTP response.", "REMOVED", EntityUtils.toString(response.getEntity()));
}
// Verify that we are not challenged.
request = new HttpGet(new URI(url.toExternalForm()));
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "null", EntityUtils.toString(response.getEntity()));
}
}
}
static class ServerSetup extends AbstractElytronSetupTask {
@Override
protected ConfigurableElement[] getConfigurableElements() {
ConfigurableElement[] elements = new ConfigurableElement[1];
// 1 - Map the application-security-domain
elements[0] = UndertowApplicationSecurityDomain.builder()
.withName("JaspiDomain")
.withSecurityDomain("ApplicationDomain")
.build();
return elements;
}
}
}
| 8,019
| 47.313253
| 127
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/jaspi/JaspiTestBase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.jaspi;
import java.net.URL;
import java.security.Permission;
import java.security.SecurityPermission;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.shared.PermissionUtils;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.wildfly.test.integration.elytron.ejb.base.WhoAmIBean;
abstract class JaspiTestBase {
@ArquillianResource
protected URL url;
final boolean ejbSupported = !Boolean.getBoolean("ts.layers") && !Boolean.getBoolean("ts.bootable");
protected static WebArchive createDeployment(final String name) {
final Package testPackage = ConfiguredJaspiTestCase.class.getPackage();
final Permission[] permissions = new Permission[] {
new SecurityPermission("getProperty.authconfigprovider.factory"),
new SecurityPermission("setProperty.authconfigfactory.provider")
};
return ShrinkWrap.create(WebArchive.class, name + ".war")
.addClasses(JaspiTestServlet.class, SimpleServerAuthModule.class, WhoAmI.class)
.addClasses(WhoAmI.class, WhoAmIBean.class, WhoAmIBeanImpl.class)
.addAsWebInfResource(Utils.getJBossWebXmlAsset("JaspiDomain"), "jboss-web.xml")
.addAsWebInfResource(testPackage, "web.xml", "web.xml")
.addAsWebInfResource(testPackage, "jboss-ejb3.xml", "jboss-ejb3.xml")
.addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(permissions), "permissions.xml");
}
}
| 2,705
| 45.655172
| 114
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/jaspi/WhoAmIBeanImpl.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.jaspi;
import jakarta.ejb.Stateless;
import org.jboss.ejb3.annotation.SecurityDomain;
/**
* Concrete implementation to allow deployment of bean.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@Stateless
@SecurityDomain("other")
public class WhoAmIBeanImpl extends org.wildfly.test.integration.elytron.ejb.base.WhoAmIBean implements WhoAmI {
}
| 1,455
| 38.351351
| 112
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/jaspi/SimpleServerAuthModule.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.jaspi;
import static org.wildfly.common.Assert.checkNotNullParam;
import java.io.IOException;
import java.security.Principal;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import jakarta.security.auth.message.AuthException;
import jakarta.security.auth.message.AuthStatus;
import jakarta.security.auth.message.MessageInfo;
import jakarta.security.auth.message.MessagePolicy;
import jakarta.security.auth.message.callback.CallerPrincipalCallback;
import jakarta.security.auth.message.callback.GroupPrincipalCallback;
import jakarta.security.auth.message.callback.PasswordValidationCallback;
import jakarta.security.auth.message.module.ServerAuthModule;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.wildfly.security.auth.principal.NamePrincipal;
/**
* A simple {@link ServerAuthModule} implementation.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
public class SimpleServerAuthModule implements ServerAuthModule {
private static final String AUTH_TYPE = "jakarta.servlet.http.authType";
private static final String SESSION = "jakarta.servlet.http.registerSession";
static final String ANONYMOUS = "anonymous";
private static final String AUTH_TYPE_HEADER = "X-AUTH-TYPE";
private static final String USERNAME_HEADER = "X-USERNAME";
private static final String PASSWORD_HEADER = "X-PASSWORD";
private static final String ROLES_HEADER = "X-ROLES";
private static final String MESSAGE_HEADER = "X-MESSAGE";
private static final String SESSION_HEADER = "X-SESSION";
private boolean selfValidating;
private CallbackHandler callbackHandler;
/**
* Roles to be applied to every validated identity.
*/
private String[] defaultRoles = null;
public void initialize(MessagePolicy requestPolicy, MessagePolicy responsePolicy, CallbackHandler handler, Map options)
throws AuthException {
this.callbackHandler = checkNotNullParam("handler", handler);
this.selfValidating = "self-validating".equals(options.get("mode"));
if (options.containsKey("default-roles")) {
defaultRoles = String.valueOf(options.get("default-roles")).split(",");
}
}
public Class[] getSupportedMessageTypes() {
return new Class[] { HttpServletRequest.class, HttpServletResponse.class };
}
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException {
HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();
final String authType = request.getHeader(AUTH_TYPE_HEADER);
final Principal currentPrincipal = request.getUserPrincipal();
if (currentPrincipal != null && currentPrincipal.getName().equals("anonymous") == false) {
handle(new CallerPrincipalCallback(clientSubject, currentPrincipal));
if (authType != null) {
messageInfo.getMap().put(AUTH_TYPE, authType);
}
return AuthStatus.SUCCESS;
}
final String username = request.getHeader(USERNAME_HEADER);
final String password = request.getHeader(PASSWORD_HEADER);
final String roles = request.getHeader(ROLES_HEADER);
final String session = request.getHeader(SESSION_HEADER);
if (username == null || username.length() == 0 || ((password == null || password.length() == 0) && !ANONYMOUS.equals(username))) {
sendChallenge(response);
return AuthStatus.SEND_CONTINUE;
}
final boolean validated;
if ("anonymous".equals(username)) {
validated = true; // Skip Authentication.
} else if (selfValidating) {
// In this mode the ServerAuthModule is taking over it's own validation and only using Callbacks to establish the identity.
validated = "user1".equals(username) && "password1".equals(password);
} else {
PasswordValidationCallback pvc = new PasswordValidationCallback(serviceSubject, username, password.toCharArray());
try {
handle(pvc);
} finally {
pvc.clearPassword();
}
validated = pvc.getResult();
}
if (validated) {
if ("anonymous".equals(username)) {
handle(new CallerPrincipalCallback(clientSubject, (Principal) null));
} else {
handle(new CallerPrincipalCallback(clientSubject, new NamePrincipal(username)));
}
if (roles != null) {
handle(new GroupPrincipalCallback(clientSubject, roles.split(",")));
}
if (defaultRoles != null) {
handle(new GroupPrincipalCallback(clientSubject, defaultRoles));
}
Map map = messageInfo.getMap();
if (authType != null) {
map.put(AUTH_TYPE, authType);
}
if ("register".equals(session)) {
System.out.println("Requesting session registration");
map.put(SESSION, Boolean.TRUE.toString());
}
return AuthStatus.SUCCESS;
} else {
// It is a failure as authentication was deliberately attempted and the supplied username / password failed validation.
sendChallenge(response);
return AuthStatus.SEND_FAILURE;
}
}
public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException {}
public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException {
return AuthStatus.SEND_SUCCESS;
}
private void handle(final Callback... callbacks) throws AuthException {
try {
callbackHandler.handle(callbacks);
} catch (IOException | UnsupportedCallbackException e) {
e.printStackTrace();
throw new AuthException(e.getMessage());
}
}
private static void sendChallenge(HttpServletResponse response) {
response.addHeader(MESSAGE_HEADER, "Please resubmit the request with a username specified using the X-USERNAME and a password specified using the X-PASSWORD header.");
response.setStatus(401);
}
}
| 7,678
| 40.961749
| 175
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/jaspi/WhoAmI.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.jaspi;
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,629
| 32.958333
| 93
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/principaltransformers/RegexValidatingPrincipalTransformerTestCase.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.wildfly.test.integration.elytron.principaltransformers;
import java.net.MalformedURLException;
import java.net.URL;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
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.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.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.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.test.security.common.elytron.PropertyFileBasedDomain;
/**
* Test case for 'regex-validating-principal-transformer' Elytron subsystem resource.
*
* @author olukas
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({RegexValidatingPrincipalTransformerTestCase.SetupTask.class})
public class RegexValidatingPrincipalTransformerTestCase {
private static final String DEP_SECURITY_DOMAIN_MATCH = "regex-validating-principal-transformer-domain-match";
private static final String DEP_SECURITY_DOMAIN_NOT_MATCH = "regex-validating-principal-transformer-domain-not-match";
private static final String USER = "user";
private static final String USER2 = "user2";
private static final String PASSWORD = "password";
private static final String ROLE = "JBossAdmin";
@Deployment(name = DEP_SECURITY_DOMAIN_MATCH)
public static WebArchive deploymentMatch() {
return createDeployment(DEP_SECURITY_DOMAIN_MATCH);
}
@Deployment(name = DEP_SECURITY_DOMAIN_NOT_MATCH)
public static WebArchive deploymentNotMatch() {
return createDeployment(DEP_SECURITY_DOMAIN_NOT_MATCH);
}
private static WebArchive createDeployment(String domain) {
final WebArchive war = ShrinkWrap.create(WebArchive.class, domain + ".war");
war.addClasses(SimpleServlet.class);
war.addClasses(SimpleSecuredServlet.class);
war.addAsWebInfResource(RegexValidatingPrincipalTransformerTestCase.class.getPackage(), "principal-transformer-web.xml", "web.xml");
war.addAsWebInfResource(Utils.getJBossWebXmlAsset(domain), "jboss-web.xml");
return war;
}
/**
* Test that validation in 'regex-validating-principal-transformer' fails in case when attribute 'match' is set to true and
* user name does not match the pattern.
*/
@Test
@OperateOnDeployment(DEP_SECURITY_DOMAIN_MATCH)
public void testMatchTrueAndUsernameDoesNotMatch(@ArquillianResource URL webAppURL) throws Exception {
URL url = prepareUrl(webAppURL);
Utils.makeCallWithBasicAuthn(url, USER, PASSWORD, SC_UNAUTHORIZED);
}
/**
* Test that validation in 'regex-validating-principal-transformer' succeed in case when attribute 'match' is set to true
* and user name matches the pattern.
*/
@Test
@OperateOnDeployment(DEP_SECURITY_DOMAIN_MATCH)
public void testMatchTrueAndUsernameMatches(@ArquillianResource URL webAppURL) throws Exception {
URL url = prepareUrl(webAppURL);
Utils.makeCallWithBasicAuthn(url, USER2, PASSWORD, SC_OK);
}
/**
* Test that validation in 'regex-validating-principal-transformer' succeed in case when attribute 'match' is set to false
* and user name does not match the pattern.
*/
@Test
@OperateOnDeployment(DEP_SECURITY_DOMAIN_NOT_MATCH)
public void testMatchFalseAndUsernameDoesNotMatch(@ArquillianResource URL webAppURL) throws Exception {
URL url = prepareUrl(webAppURL);
Utils.makeCallWithBasicAuthn(url, USER, PASSWORD, SC_OK);
}
/**
* Test that validation in 'regex-validating-principal-transformer' fails in case when attribute 'match' is set to false and
* user name matches the pattern.
*/
@Test
@OperateOnDeployment(DEP_SECURITY_DOMAIN_NOT_MATCH)
public void testMatchFalseAndUsernameMatches(@ArquillianResource URL webAppURL) throws Exception {
URL url = prepareUrl(webAppURL);
Utils.makeCallWithBasicAuthn(url, USER2, PASSWORD, SC_UNAUTHORIZED);
}
private URL prepareUrl(URL url) throws MalformedURLException {
return new URL(url.toExternalForm() + SimpleSecuredServlet.SERVLET_PATH.substring(1));
}
static class SetupTask implements ServerSetupTask {
private static final String ELYTRON_SECURITY_MATCH = "elytronDomainMatch";
private static final String ELYTRON_SECURITY_NOT_MATCH = "elytronDomainNotMatch";
private static final String PRINCIPAL_TRANSFORMER_MATCH = "transformerMatch";
private static final String PRINCIPAL_TRANSFORMER_NOT_MATCH = "transformerNotMatch";
private static final String PREDEFINED_HTTP_SERVER_MECHANISM_FACTORY = "global";
private PropertyFileBasedDomain domainMatch;
private PropertyFileBasedDomain domainNotMatch;
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
domainMatch = prepareSingleConfiguration(cli, ELYTRON_SECURITY_MATCH, PRINCIPAL_TRANSFORMER_MATCH, DEP_SECURITY_DOMAIN_MATCH,
"/subsystem=elytron/regex-validating-principal-transformer=%s:add(pattern=user\\\\d+,match=true)");
domainNotMatch = prepareSingleConfiguration(cli, ELYTRON_SECURITY_NOT_MATCH, PRINCIPAL_TRANSFORMER_NOT_MATCH, DEP_SECURITY_DOMAIN_NOT_MATCH,
"/subsystem=elytron/regex-validating-principal-transformer=%s:add(pattern=user\\\\d+,match=false)");
}
ServerReload.reloadIfRequired(managementClient);
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
removeSingleConfiguration(cli, ELYTRON_SECURITY_NOT_MATCH, PRINCIPAL_TRANSFORMER_NOT_MATCH, DEP_SECURITY_DOMAIN_NOT_MATCH, domainNotMatch);
removeSingleConfiguration(cli, ELYTRON_SECURITY_MATCH, PRINCIPAL_TRANSFORMER_MATCH, DEP_SECURITY_DOMAIN_MATCH, domainMatch);
}
ServerReload.reloadIfRequired(managementClient);
}
private PropertyFileBasedDomain prepareSingleConfiguration(CLIWrapper cli, String elytronName, String transformerName,
String deploymentName, String addTransformerCli)
throws Exception {
PropertyFileBasedDomain domain = PropertyFileBasedDomain.builder().withName(elytronName)
.withUser(USER, PASSWORD, ROLE)
.withUser(USER2, PASSWORD, ROLE)
.build();
domain.create(cli);
cli.sendLine(String.format(addTransformerCli, transformerName));
cli.sendLine(String.format("/subsystem=elytron/security-domain=%s:write-attribute(name=realms[0].principal-transformer,value=%s)",
elytronName, transformerName));
cli.sendLine(String.format(
"/subsystem=elytron/http-authentication-factory=%1$s:add(http-server-mechanism-factory=%2$s,security-domain=%1$s,"
+ "mechanism-configurations=[{mechanism-name=BASIC,mechanism-realm-configurations=[{realm-name=\"%1$s\"}]}])",
elytronName, PREDEFINED_HTTP_SERVER_MECHANISM_FACTORY));
cli.sendLine(String.format(
"/subsystem=undertow/application-security-domain=%s:add(http-authentication-factory=%s)",
deploymentName, elytronName));
return domain;
}
private void removeSingleConfiguration(CLIWrapper cli, String elytronName, String transformerName,
String deploymentName, PropertyFileBasedDomain domain) throws Exception {
cli.sendLine(String.format(
"/subsystem=elytron/security-domain=%s:undefine-attribute(name=realms[0].principal-transformer)",
elytronName));
cli.sendLine(String.format("/subsystem=undertow/application-security-domain=%s:remove()", deploymentName));
cli.sendLine(String.format("/subsystem=elytron/http-authentication-factory=%s:remove()", elytronName));
cli.sendLine(String.format("/subsystem=elytron/regex-validating-principal-transformer=%s:remove()", transformerName));
domain.remove(cli);
}
}
}
| 10,125
| 50.401015
| 156
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/principaltransformers/RegexPrincipalTransformerTestCase.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.wildfly.test.integration.elytron.principaltransformers;
import java.net.MalformedURLException;
import java.net.URL;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
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.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.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.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.test.security.common.elytron.PropertyFileBasedDomain;
/**
* Test case for 'regex-principal-transformer' Elytron subsystem resource.
*
* @author olukas
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({RegexPrincipalTransformerTestCase.SetupTask.class})
public class RegexPrincipalTransformerTestCase {
private static final String DEP_SECURITY_DOMAIN_E = "regex-principal-transformer-domain-e";
private static final String DEP_SECURITY_DOMAIN_S = "regex-principal-transformer-domain-s";
private static final String SOME_USER = "someuser";
private static final String PASSWORD = "password";
private static final String ROLE = "JBossAdmin";
@Deployment(name = DEP_SECURITY_DOMAIN_E)
public static WebArchive deploymentE() {
return createDeployment(DEP_SECURITY_DOMAIN_E);
}
@Deployment(name = DEP_SECURITY_DOMAIN_S)
public static WebArchive deploymentS() {
return createDeployment(DEP_SECURITY_DOMAIN_S);
}
private static WebArchive createDeployment(String domain) {
final WebArchive war = ShrinkWrap.create(WebArchive.class, domain + ".war");
war.addClasses(SimpleServlet.class);
war.addClasses(SimpleSecuredServlet.class);
war.addAsWebInfResource(RegexPrincipalTransformerTestCase.class.getPackage(), "principal-transformer-web.xml", "web.xml");
war.addAsWebInfResource(Utils.getJBossWebXmlAsset(domain), "jboss-web.xml");
return war;
}
/**
* Test that even existing user name is transformed through used 'regex-principal-transformer'.
*/
@Test
@OperateOnDeployment(DEP_SECURITY_DOMAIN_E)
public void testCorrectUserTransformToWrong(@ArquillianResource URL webAppURL) throws Exception {
URL url = prepareUrl(webAppURL);
Utils.makeCallWithBasicAuthn(url, SOME_USER, PASSWORD, SC_UNAUTHORIZED);
}
/**
* Test that if attribute 'replace-all' is set to false in 'regex-principal-transformer', then only first occurrence of
* pattern is rewritten.
*/
@Test
@OperateOnDeployment(DEP_SECURITY_DOMAIN_E)
public void testCorrectTransformReplaceFirst(@ArquillianResource URL webAppURL) throws Exception {
URL url = prepareUrl(webAppURL);
Utils.makeCallWithBasicAuthn(url, "somruser", PASSWORD, SC_OK);
}
/**
* Test that pattern does not occurs in user name, then the same user name is returned (no transformation is done).
*/
@Test
@OperateOnDeployment(DEP_SECURITY_DOMAIN_S)
public void testNoTransformForPatternNotMatch(@ArquillianResource URL webAppURL) throws Exception {
URL url = prepareUrl(webAppURL);
Utils.makeCallWithBasicAuthn(url, SOME_USER, PASSWORD, SC_OK);
}
/**
* Test that if attribute 'replace-all' is set to true in 'regex-principal-transformer', then all occurrences of pattern are
* rewritten.
*/
@Test
@OperateOnDeployment(DEP_SECURITY_DOMAIN_S)
public void testCorrectTransformReplaceAll(@ArquillianResource URL webAppURL) throws Exception {
URL url = prepareUrl(webAppURL);
Utils.makeCallWithBasicAuthn(url, "1omeu234er", PASSWORD, SC_OK);
}
private URL prepareUrl(URL url) throws MalformedURLException {
return new URL(url.toExternalForm() + SimpleSecuredServlet.SERVLET_PATH.substring(1));
}
static class SetupTask implements ServerSetupTask {
private static final String ELYTRON_SECURITY_E = "elytronDomainE";
private static final String ELYTRON_SECURITY_S = "elytronDomainS";
private static final String PRINCIPAL_TRANSFORMER_E = "transformerE";
private static final String PRINCIPAL_TRANSFORMER_S = "transformerS";
private static final String PREDEFINED_HTTP_SERVER_MECHANISM_FACTORY = "global";
private PropertyFileBasedDomain domainE;
private PropertyFileBasedDomain domainS;
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
domainE = prepareSingleConfiguration(cli, ELYTRON_SECURITY_E, PRINCIPAL_TRANSFORMER_E, DEP_SECURITY_DOMAIN_E,
"/subsystem=elytron/regex-principal-transformer=%s:add(pattern=(r),replacement=e,replace-all=false)");
domainS = prepareSingleConfiguration(cli, ELYTRON_SECURITY_S, PRINCIPAL_TRANSFORMER_S, DEP_SECURITY_DOMAIN_S,
"/subsystem=elytron/regex-principal-transformer=%s:add(pattern=(\\\\d+),replacement=s,replace-all=true)");
}
ServerReload.reloadIfRequired(managementClient);
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
removeSingleConfiguration(cli, ELYTRON_SECURITY_S, PRINCIPAL_TRANSFORMER_S, DEP_SECURITY_DOMAIN_S, domainS);
removeSingleConfiguration(cli, ELYTRON_SECURITY_E, PRINCIPAL_TRANSFORMER_E, DEP_SECURITY_DOMAIN_E, domainE);
}
ServerReload.reloadIfRequired(managementClient);
}
private PropertyFileBasedDomain prepareSingleConfiguration(CLIWrapper cli, String elytronName, String transformerName,
String deploymentName, String addTransformerCli)
throws Exception {
PropertyFileBasedDomain domain = PropertyFileBasedDomain.builder().withName(elytronName)
.withUser(SOME_USER, PASSWORD, ROLE)
.build();
domain.create(cli);
cli.sendLine(String.format(addTransformerCli, transformerName));
cli.sendLine(String.format("/subsystem=elytron/security-domain=%s:write-attribute(name=realms[0].principal-transformer,value=%s)",
elytronName, transformerName));
cli.sendLine(String.format(
"/subsystem=elytron/http-authentication-factory=%1$s:add(http-server-mechanism-factory=%2$s,security-domain=%1$s,"
+ "mechanism-configurations=[{mechanism-name=BASIC,mechanism-realm-configurations=[{realm-name=\"%1$s\"}]}])",
elytronName, PREDEFINED_HTTP_SERVER_MECHANISM_FACTORY));
cli.sendLine(String.format(
"/subsystem=undertow/application-security-domain=%s:add(http-authentication-factory=%s)",
deploymentName, elytronName));
return domain;
}
private void removeSingleConfiguration(CLIWrapper cli, String elytronName, String transformerName,
String deploymentName, PropertyFileBasedDomain domain) throws Exception {
cli.sendLine(String.format(
"/subsystem=elytron/security-domain=%s:undefine-attribute(name=realms[0].principal-transformer)",
elytronName));
cli.sendLine(String.format("/subsystem=undertow/application-security-domain=%s:remove()", deploymentName));
cli.sendLine(String.format("/subsystem=elytron/http-authentication-factory=%s:remove()", elytronName));
cli.sendLine(String.format("/subsystem=elytron/regex-principal-transformer=%s:remove()", transformerName));
domain.remove(cli);
}
}
}
| 9,576
| 48.621762
| 142
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/principaltransformers/ConstantPrincipalTransformerTestCase.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
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.principaltransformers;
import java.net.URL;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
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.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.RolesPrintingServletUtils;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.RolePrintingServlet;
import org.jboss.as.test.shared.ServerReload;
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.security.common.elytron.PropertyFileBasedDomain;
/**
* Test case for 'constant-principal-transformer' Elytron subsystem resource.
*
* @author olukas
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ConstantPrincipalTransformerTestCase.SetupTask.class})
public class ConstantPrincipalTransformerTestCase {
private static final String DEP_SECURITY_DOMAIN = "contant-principal-transformer-domain";
private static final String USER1 = "user1";
private static final String USER2 = "user2";
private static final String PASSWORD1 = "password1";
private static final String PASSWORD2 = "password2";
private static final String ROLE1 = "role1";
private static final String ROLE2 = "role2";
private final String[] allPossibleRoles = {ROLE1, ROLE2};
@Deployment(name = DEP_SECURITY_DOMAIN)
public static WebArchive securityDomainWithMappingModuleDeployment() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, DEP_SECURITY_DOMAIN + ".war");
war.addClasses(RolePrintingServlet.class);
war.addAsWebInfResource(ConstantPrincipalTransformerTestCase.class.getPackage(), "principal-transformer-web.xml", "web.xml");
war.addAsWebInfResource(Utils.getJBossWebXmlAsset(DEP_SECURITY_DOMAIN), "jboss-web.xml");
return war;
}
/**
* Test whether name of any user passed to security domain is transformed into constant defined in used
* 'constant-principal-transformer'. Test also checks that authentication passes for correct password. It also checks that
* correct role is assigned to transformed user.
*/
@Test
@OperateOnDeployment(DEP_SECURITY_DOMAIN)
public void testPassingAnyUserAndCorrectPassword(@ArquillianResource URL webAppURL) throws Exception {
URL prepareRolePrintingUrl = RolesPrintingServletUtils.prepareRolePrintingUrl(webAppURL, allPossibleRoles);
String responseBody = Utils.makeCallWithBasicAuthn(prepareRolePrintingUrl, "anyUser", PASSWORD1, SC_OK);
String[] expectedRoles = {ROLE1};
RolesPrintingServletUtils.assertExpectedRoles(responseBody, allPossibleRoles, expectedRoles);
}
/**
* Test checks that authentication fails for incorrect password if 'constant-principal-transformer' is used.
*/
@Test
@OperateOnDeployment(DEP_SECURITY_DOMAIN)
public void testPassingWrongPassword(@ArquillianResource URL webAppURL) throws Exception {
URL prepareRolePrintingUrl = RolesPrintingServletUtils.prepareRolePrintingUrl(webAppURL, allPossibleRoles);
Utils.makeCallWithBasicAuthn(prepareRolePrintingUrl, USER1, "wrongPassword", SC_UNAUTHORIZED);
}
/**
* Test that even existing user name is transformed into constant defined in used 'constant-principal-transformer'. It
* checks that if password of existing user is passed to authentication, than authentication fails.
*/
@Test
@OperateOnDeployment(DEP_SECURITY_DOMAIN)
public void testPassingExistingUserAndHisPassword(@ArquillianResource URL webAppURL) throws Exception {
URL prepareRolePrintingUrl = RolesPrintingServletUtils.prepareRolePrintingUrl(webAppURL, allPossibleRoles);
Utils.makeCallWithBasicAuthn(prepareRolePrintingUrl, USER2, PASSWORD2, SC_UNAUTHORIZED);
}
/**
* Test that even existing user name is transformed into constant defined in used 'constant-principal-transformer'. It
* checks that if password of transformed user is passed to authentication, than authentication passes. It also checks that
* correct role is assigned to transformed user.
*/
@Test
@OperateOnDeployment(DEP_SECURITY_DOMAIN)
public void testPassingExistingUserAndCorrectPassword(@ArquillianResource URL webAppURL) throws Exception {
URL prepareRolePrintingUrl = RolesPrintingServletUtils.prepareRolePrintingUrl(webAppURL, allPossibleRoles);
String responseBody = Utils.makeCallWithBasicAuthn(prepareRolePrintingUrl, USER2, PASSWORD1, SC_OK);
String[] expectedRoles = {ROLE1};
RolesPrintingServletUtils.assertExpectedRoles(responseBody, allPossibleRoles, expectedRoles);
}
static class SetupTask implements ServerSetupTask {
private static final String ELYTRON_SECURITY = "elytronDomain";
private static final String PRINCIPAL_TRANSFORMER = "transformer";
private static final String PREDEFINED_HTTP_SERVER_MECHANISM_FACTORY = "global";
PropertyFileBasedDomain domain;
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
domain = PropertyFileBasedDomain.builder().withName(ELYTRON_SECURITY)
.withUser(USER1, PASSWORD1, ROLE1)
.withUser(USER2, PASSWORD2, ROLE2)
.build();
domain.create(cli);
cli.sendLine(String.format(
"/subsystem=elytron/constant-principal-transformer=%s:add(constant=%s)",
PRINCIPAL_TRANSFORMER, USER1));
cli.sendLine(String.format(
"/subsystem=elytron/security-domain=%s:write-attribute(name=realms[0].principal-transformer,value=%s)",
ELYTRON_SECURITY, PRINCIPAL_TRANSFORMER));
cli.sendLine(String.format(
"/subsystem=elytron/http-authentication-factory=%1$s:add(http-server-mechanism-factory=%2$s,security-domain=%1$s,"
+ "mechanism-configurations=[{mechanism-name=BASIC,mechanism-realm-configurations=[{realm-name=\"%1$s\"}]}])",
ELYTRON_SECURITY, PREDEFINED_HTTP_SERVER_MECHANISM_FACTORY));
cli.sendLine(String.format(
"/subsystem=undertow/application-security-domain=%s:add(http-authentication-factory=%s)",
DEP_SECURITY_DOMAIN, ELYTRON_SECURITY));
}
ServerReload.reloadIfRequired(managementClient);
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
cli.sendLine(String.format(
"/subsystem=elytron/security-domain=%s:undefine-attribute(name=realms[0].principal-transformer)",
ELYTRON_SECURITY));
cli.sendLine(String.format("/subsystem=undertow/application-security-domain=%s:remove()", DEP_SECURITY_DOMAIN));
cli.sendLine(String.format("/subsystem=elytron/http-authentication-factory=%s:remove()", ELYTRON_SECURITY));
cli.sendLine(String.format("/subsystem=elytron/constant-principal-transformer=%s:remove()", PRINCIPAL_TRANSFORMER));
domain.remove(cli);
}
ServerReload.reloadIfRequired(managementClient);
}
}
}
| 9,204
| 51.301136
| 138
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/principaltransformers/CasePrincipalTransformerTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, 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.principaltransformers;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
import java.net.MalformedURLException;
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.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.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.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.test.security.common.elytron.PropertyFileBasedDomain;
/**
* Test case for 'case-principal-transformer' Elytron subsystem resource.
*
* @author Sonia Zaldana Calles <szaldana@redhat.com>
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({CasePrincipalTransformerTestCase.SetupTask.class})
public class CasePrincipalTransformerTestCase {
private static final String UPPER_CASE_SECURITY_DOMAIN = "upper-case-principal-domain";
private static final String LOWER_CASE_SECURITY_DOMAIN = "lower-case-principal-domain";
private static final String WITHOUT_TRANSFORMER_SECURITY_DOMAIN = "without-case-principal-domain";
private static final String UPPER_USER = "USER1";
private static final String LOWER_USER = "user1";
private static final String PASSWORD = "password1";
private static final String ROLE = "JBossAdmin";
@Deployment(name = UPPER_CASE_SECURITY_DOMAIN)
public static WebArchive createUpperCaseDeployment() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, UPPER_CASE_SECURITY_DOMAIN + ".war");
war.addClasses(SimpleServlet.class);
war.addClasses(SimpleSecuredServlet.class);
war.addAsWebInfResource(ConstantPrincipalTransformerTestCase.class.getPackage(), "principal-transformer-web.xml", "web.xml");
war.addAsWebInfResource(Utils.getJBossWebXmlAsset(UPPER_CASE_SECURITY_DOMAIN), "jboss-web.xml");
return war;
}
@Deployment(name = LOWER_CASE_SECURITY_DOMAIN)
public static WebArchive createLowerCaseDeployment() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, LOWER_CASE_SECURITY_DOMAIN + ".war");
war.addClasses(SimpleServlet.class);
war.addClasses(SimpleSecuredServlet.class);
war.addAsWebInfResource(ConstantPrincipalTransformerTestCase.class.getPackage(), "principal-transformer-web.xml", "web.xml");
war.addAsWebInfResource(Utils.getJBossWebXmlAsset(LOWER_CASE_SECURITY_DOMAIN), "jboss-web.xml");
return war;
}
@Deployment(name = WITHOUT_TRANSFORMER_SECURITY_DOMAIN)
public static WebArchive createWithoutTransformerDeployment() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, WITHOUT_TRANSFORMER_SECURITY_DOMAIN + ".war");
war.addClasses(SimpleServlet.class);
war.addClasses(SimpleSecuredServlet.class);
war.addAsWebInfResource(ConstantPrincipalTransformerTestCase.class.getPackage(), "principal-transformer-web.xml", "web.xml");
war.addAsWebInfResource(Utils.getJBossWebXmlAsset(WITHOUT_TRANSFORMER_SECURITY_DOMAIN), "jboss-web.xml");
return war;
}
/**
* Test whether name of user passed to security domain is adjusted into upper case with
* the 'case-principal-transformer'. Test also checks that authentication passes for correct password.
*/
@Test
@OperateOnDeployment(UPPER_CASE_SECURITY_DOMAIN)
public void testPassingExistingUserUpperCase(@ArquillianResource URL webAppURL) throws Exception {
URL url = prepareUrl(webAppURL);
Utils.makeCallWithBasicAuthn(url, LOWER_USER, PASSWORD, SC_OK); // UPPER_CASE ("USER1") is stored in the realm
}
/**
* Test checks that authentication fails for incorrect password and incorrect user
* if upper case 'case-principal-transformer is used.
*/
@Test
@OperateOnDeployment(UPPER_CASE_SECURITY_DOMAIN)
public void testPassingNonExistingUserWithUpperCase(@ArquillianResource URL webAppURL) throws Exception {
URL url = prepareUrl(webAppURL);
Utils.makeCallWithBasicAuthn(url, "wrongUser", PASSWORD, SC_UNAUTHORIZED);
}
/**
* Tests whether authentication fails when the principal transformer is not configured in the domain.
*/
@Test
@OperateOnDeployment(WITHOUT_TRANSFORMER_SECURITY_DOMAIN)
public void testPassingExistingUserWithoutTransformer(@ArquillianResource URL webAppUrl) throws Exception {
URL url = prepareUrl(webAppUrl);
Utils.makeCallWithBasicAuthn(url, LOWER_USER, PASSWORD, SC_UNAUTHORIZED); // UPPER_USER ("USER1") is in the realm
}
/**
* Test whether name of user passed to security domain is adjusted into lower case with
* the 'case-principal-transformer'. Test also checks that authentication passes for correct password.
*/
@Test
@OperateOnDeployment(LOWER_CASE_SECURITY_DOMAIN)
public void testPassingExistingUserWithLowerCase(@ArquillianResource URL webAppUrl) throws Exception {
URL url = prepareUrl(webAppUrl);
Utils.makeCallWithBasicAuthn(url, UPPER_USER, PASSWORD, SC_OK); // LOWER_USER ("user1") is in the realm
}
private URL prepareUrl(URL url) throws MalformedURLException {
return new URL(url.toExternalForm() + SimpleSecuredServlet.SERVLET_PATH.substring(1));
}
static class SetupTask implements ServerSetupTask {
private static final String UPPER_TRANSFORMER_DOMAIN_NAME = "withUpperTransformerDomain";
private static final String LOWER_TRANSFORMER_DOMAIN_NAME = "withLowerTransformerDomain";
private static final String WITHOUT_TRANSFORMER_DOMAIN_NAME = "withoutTransformerDomain";
private static final String UPPER_PRINCIPAL_TRANSFORMER = "upperTransformer";
private static final String LOWER_PRINCIPAL_TRANSFORMER = "lowerTransformer";
private static final String PREDEFINED_HTTP_SERVER_MECHANISM_FACTORY = "global";
PropertyFileBasedDomain domainWithUpperTransformer;
PropertyFileBasedDomain domainWithLowerTransformer;
PropertyFileBasedDomain domainWithoutTransformer;
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
setUpTestDomain(domainWithUpperTransformer, UPPER_CASE_SECURITY_DOMAIN, UPPER_TRANSFORMER_DOMAIN_NAME, UPPER_USER, PASSWORD, ROLE, UPPER_PRINCIPAL_TRANSFORMER, true);
setUpTestDomain(domainWithLowerTransformer, LOWER_CASE_SECURITY_DOMAIN, LOWER_TRANSFORMER_DOMAIN_NAME, LOWER_USER, PASSWORD, ROLE, LOWER_PRINCIPAL_TRANSFORMER, false);
setUpTestDomain(domainWithoutTransformer, WITHOUT_TRANSFORMER_SECURITY_DOMAIN, WITHOUT_TRANSFORMER_DOMAIN_NAME, UPPER_USER, PASSWORD, ROLE); // no transformer
ServerReload.reloadIfRequired(managementClient);
}
public void setUpTestDomain(PropertyFileBasedDomain domain, String testDomain, String domainName, String user, String password, String role, String transformerName, boolean upperCase) throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
domain = PropertyFileBasedDomain.builder().withName(domainName)
.withUser(user, password, role)
.build();
domain.create(cli);
// optionally sets up a transformer
if (transformerName != null) {
cli.sendLine(String.format(
"/subsystem=elytron/case-principal-transformer=%s:add(upper-case=%s)",
transformerName, upperCase));
cli.sendLine(String.format(
"/subsystem=elytron/security-domain=%s:write-attribute(name=realms[0].principal-transformer,value=%s)",
domainName, transformerName));
}
cli.sendLine(String.format(
"/subsystem=elytron/http-authentication-factory=%1$s:add(http-server-mechanism-factory=%2$s,security-domain=%1$s,"
+ "mechanism-configurations=[{mechanism-name=BASIC,mechanism-realm-configurations=[{realm-name=\"%1$s\"}]}])",
domainName, PREDEFINED_HTTP_SERVER_MECHANISM_FACTORY));
cli.sendLine(String.format(
"/subsystem=undertow/application-security-domain=%s:add(http-authentication-factory=%s)",
testDomain, domainName));
}
}
public void setUpTestDomain(PropertyFileBasedDomain domain, String testDomain, String domainName, String user, String password, String role) throws Exception{
setUpTestDomain(domain, testDomain, domainName, user, password, role, null, false);
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
tearDownTestDomain(domainWithUpperTransformer, UPPER_CASE_SECURITY_DOMAIN, UPPER_TRANSFORMER_DOMAIN_NAME, UPPER_PRINCIPAL_TRANSFORMER);
tearDownTestDomain(domainWithLowerTransformer, LOWER_CASE_SECURITY_DOMAIN, LOWER_TRANSFORMER_DOMAIN_NAME, LOWER_PRINCIPAL_TRANSFORMER);
tearDownTestDomain(domainWithoutTransformer, WITHOUT_TRANSFORMER_SECURITY_DOMAIN, WITHOUT_TRANSFORMER_DOMAIN_NAME);
ServerReload.reloadIfRequired(managementClient);
}
public void tearDownTestDomain(PropertyFileBasedDomain domain, String testDomain, String domainName, String transformerName) throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
if (transformerName != null) {
cli.sendLine(String.format(
"/subsystem=elytron/security-domain=%s:undefine-attribute(name=realms[0].principal-transformer)",
transformerName));
}
cli.sendLine(String.format("/subsystem=undertow/application-security-domain=%s:remove()", testDomain));
cli.sendLine(String.format("/subsystem=elytron/http-authentication-factory=%s:remove()", domainName));
if (transformerName != null) {
cli.sendLine(String.format("/subsystem=elytron/case-principal-transformer=%s:remove()", transformerName));
}
domain.remove(cli);
}
}
public void tearDownTestDomain(PropertyFileBasedDomain domain, String testDomain, String domainName) throws Exception {
tearDownTestDomain(domain, testDomain, domainName, null);
}
}
}
| 12,370
| 51.867521
| 210
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/principaltransformers/ChainedPrincipalTransformerTestCase.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.wildfly.test.integration.elytron.principaltransformers;
import java.net.MalformedURLException;
import java.net.URL;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
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.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.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.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.test.security.common.elytron.PropertyFileBasedDomain;
/**
* Test case for 'chained-principal-transformer' Elytron subsystem resource. This test cases uses also
* 'regex-principal-transformer' - it means that any issue in 'regex-principal-transformer' can affect this test case.
*
* @author olukas
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ChainedPrincipalTransformerTestCase.SetupTask.class})
public class ChainedPrincipalTransformerTestCase {
private static final String DEP_SECURITY_DOMAIN_TWO = "chained-principal-transformer-two";
private static final String DEP_SECURITY_DOMAIN_THREE = "chained-principal-transformer-three";
private static final String DEP_SECURITY_DOMAIN_TRANSFORM_TRANSFORMED = "chained-principal-transformer-transform-transformed";
private static final String USER1 = "userAB";
private static final String USER2 = "userBAC";
private static final String USER3 = "transformerUser";
private static final String PASSWORD1 = "password1";
private static final String PASSWORD2 = "password2";
private static final String PASSWORD3 = "password3";
private static final String ROLE = "JBossAdmin";
@Deployment(name = DEP_SECURITY_DOMAIN_TWO)
public static WebArchive deploymentTwoTransformersInChain() {
return createDeployment(DEP_SECURITY_DOMAIN_TWO);
}
@Deployment(name = DEP_SECURITY_DOMAIN_THREE)
public static WebArchive deploymentThreeTransformersInChain() {
return createDeployment(DEP_SECURITY_DOMAIN_THREE);
}
@Deployment(name = DEP_SECURITY_DOMAIN_TRANSFORM_TRANSFORMED)
public static WebArchive deploymentTransformTransformed() {
return createDeployment(DEP_SECURITY_DOMAIN_TRANSFORM_TRANSFORMED);
}
private static WebArchive createDeployment(String domain) {
final WebArchive war = ShrinkWrap.create(WebArchive.class, domain + ".war");
war.addClasses(SimpleServlet.class);
war.addClasses(SimpleSecuredServlet.class);
war.addAsWebInfResource(ChainedPrincipalTransformerTestCase.class.getPackage(), "principal-transformer-web.xml", "web.xml");
war.addAsWebInfResource(Utils.getJBossWebXmlAsset(domain), "jboss-web.xml");
return war;
}
/**
* Test that in case when two principal transformers are used in 'chained-principal-transformer', then transformations
* happens in expected order.
*/
@Test
@OperateOnDeployment(DEP_SECURITY_DOMAIN_TWO)
public void testTwoTransformersInChain(@ArquillianResource URL webAppURL) throws Exception {
URL url = prepareUrl(webAppURL);
Utils.makeCallWithBasicAuthn(url, "user", PASSWORD1, SC_OK);
}
/**
* Test that in case when three principal transformers are used in 'chained-principal-transformer', then transformations
* happens in expected order.
*/
@Test
@OperateOnDeployment(DEP_SECURITY_DOMAIN_THREE)
public void testThreeTransformersInChain(@ArquillianResource URL webAppURL) throws Exception {
URL url = prepareUrl(webAppURL);
Utils.makeCallWithBasicAuthn(url, "user", PASSWORD2, SC_OK);
}
/**
* Test that transformation from second transformer is applied on transformed name obtained from first transformer.
*/
@Test
@OperateOnDeployment(DEP_SECURITY_DOMAIN_TRANSFORM_TRANSFORMED)
public void testTransformTransformed(@ArquillianResource URL webAppURL) throws Exception {
URL url = prepareUrl(webAppURL);
Utils.makeCallWithBasicAuthn(url, "transformerUTRANSFORMEDer", PASSWORD3, SC_OK);
}
private URL prepareUrl(URL url) throws MalformedURLException {
return new URL(url.toExternalForm() + SimpleSecuredServlet.SERVLET_PATH.substring(1));
}
static class SetupTask implements ServerSetupTask {
private static final String ELYTRON_SECURITY_TWO = "elytronDomainTwo";
private static final String ELYTRON_SECURITY_THREE = "elytronDomainThree";
private static final String ELYTRON_SECURITY_TRANSFORM_TRANSFORMED = "elytronDomainTransformTransformed";
private static final String PRINCIPAL_TRANSFORMER_TWO = "transformerTwo";
private static final String PRINCIPAL_TRANSFORMER_THREE = "transformerThree";
private static final String PRINCIPAL_TRANSFORMER_TRANSFORM_TRANSFORMED = "transformerTransformTransformed";
private static final String REGEX_TRANSFORMER_A = "regexTransformerA";
private static final String REGEX_TRANSFORMER_B = "regexTransformerB";
private static final String REGEX_TRANSFORMER_C = "regexTransformerC";
private static final String REGEX_TRANSFORMED_FIRST = "regexTransformer1";
private static final String REGEX_TRANSFORMED_SECOND = "regexTransformer2";
private static final String PREDEFINED_HTTP_SERVER_MECHANISM_FACTORY = "global";
private PropertyFileBasedDomain chainedTwoTransformers;
private PropertyFileBasedDomain chainedThreeTransformers;
private PropertyFileBasedDomain transformTransformed;
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
cli.sendLine(String.format("/subsystem=elytron/regex-principal-transformer=%s:add(pattern=$,replacement=A)",
REGEX_TRANSFORMER_A));
cli.sendLine(String.format("/subsystem=elytron/regex-principal-transformer=%s:add(pattern=$,replacement=B)",
REGEX_TRANSFORMER_B));
cli.sendLine(String.format("/subsystem=elytron/regex-principal-transformer=%s:add(pattern=$,replacement=C)",
REGEX_TRANSFORMER_C));
cli.sendLine(String.format("/subsystem=elytron/regex-principal-transformer=%s:add(pattern=TRANSFORM,replacement=CHANG)",
REGEX_TRANSFORMED_FIRST));
cli.sendLine(String.format("/subsystem=elytron/regex-principal-transformer=%s:add(pattern=CHANGED,replacement=s)",
REGEX_TRANSFORMED_SECOND));
chainedTwoTransformers = prepareSingleConfiguration(cli, ELYTRON_SECURITY_TWO, PRINCIPAL_TRANSFORMER_TWO,
DEP_SECURITY_DOMAIN_TWO,
"/subsystem=elytron/chained-principal-transformer=%s:add(principal-transformers=[" + REGEX_TRANSFORMER_A
+ "," + REGEX_TRANSFORMER_B + "])");
chainedThreeTransformers = prepareSingleConfiguration(cli, ELYTRON_SECURITY_THREE, PRINCIPAL_TRANSFORMER_THREE,
DEP_SECURITY_DOMAIN_THREE,
"/subsystem=elytron/chained-principal-transformer=%s:add(principal-transformers=[" + REGEX_TRANSFORMER_B
+ "," + REGEX_TRANSFORMER_A + "," + REGEX_TRANSFORMER_C + "])");
transformTransformed = prepareSingleConfiguration(cli, ELYTRON_SECURITY_TRANSFORM_TRANSFORMED,
PRINCIPAL_TRANSFORMER_TRANSFORM_TRANSFORMED, DEP_SECURITY_DOMAIN_TRANSFORM_TRANSFORMED,
"/subsystem=elytron/chained-principal-transformer=%s:add(principal-transformers=[" + REGEX_TRANSFORMED_FIRST
+ "," + REGEX_TRANSFORMED_SECOND + "])");
}
ServerReload.reloadIfRequired(managementClient);
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
removeSingleConfiguration(cli, ELYTRON_SECURITY_TWO, PRINCIPAL_TRANSFORMER_TWO,
DEP_SECURITY_DOMAIN_TWO, chainedTwoTransformers);
removeSingleConfiguration(cli, ELYTRON_SECURITY_THREE, PRINCIPAL_TRANSFORMER_THREE,
DEP_SECURITY_DOMAIN_THREE, chainedThreeTransformers);
removeSingleConfiguration(cli, ELYTRON_SECURITY_TRANSFORM_TRANSFORMED, PRINCIPAL_TRANSFORMER_TRANSFORM_TRANSFORMED,
DEP_SECURITY_DOMAIN_TRANSFORM_TRANSFORMED, transformTransformed);
cli.sendLine(String.format("/subsystem=elytron/regex-principal-transformer=%s:remove()", REGEX_TRANSFORMED_SECOND));
cli.sendLine(String.format("/subsystem=elytron/regex-principal-transformer=%s:remove()", REGEX_TRANSFORMED_FIRST));
cli.sendLine(String.format("/subsystem=elytron/regex-principal-transformer=%s:remove()", REGEX_TRANSFORMER_C));
cli.sendLine(String.format("/subsystem=elytron/regex-principal-transformer=%s:remove()", REGEX_TRANSFORMER_B));
cli.sendLine(String.format("/subsystem=elytron/regex-principal-transformer=%s:remove()", REGEX_TRANSFORMER_A));
}
ServerReload.reloadIfRequired(managementClient);
}
private PropertyFileBasedDomain prepareSingleConfiguration(CLIWrapper cli, String elytronName, String transformerName,
String deploymentName, String addTransformerCli)
throws Exception {
PropertyFileBasedDomain domain = PropertyFileBasedDomain.builder().withName(elytronName)
.withUser(USER1, PASSWORD1, ROLE)
.withUser(USER2, PASSWORD2, ROLE)
.withUser(USER3, PASSWORD3, ROLE)
.build();
domain.create(cli);
cli.sendLine(String.format(addTransformerCli, transformerName));
cli.sendLine(String.format("/subsystem=elytron/security-domain=%s:write-attribute(name=realms[0].principal-transformer,value=%s)",
elytronName, transformerName));
cli.sendLine(String.format(
"/subsystem=elytron/http-authentication-factory=%1$s:add(http-server-mechanism-factory=%2$s,security-domain=%1$s,"
+ "mechanism-configurations=[{mechanism-name=BASIC,mechanism-realm-configurations=[{realm-name=\"%1$s\"}]}])",
elytronName, PREDEFINED_HTTP_SERVER_MECHANISM_FACTORY));
cli.sendLine(String.format(
"/subsystem=undertow/application-security-domain=%s:add(http-authentication-factory=%s)",
deploymentName, elytronName));
return domain;
}
private void removeSingleConfiguration(CLIWrapper cli, String elytronName, String transformerName,
String deploymentName, PropertyFileBasedDomain domain) throws Exception {
cli.sendLine(String.format(
"/subsystem=elytron/security-domain=%s:undefine-attribute(name=realms[0].principal-transformer)",
elytronName));
cli.sendLine(String.format("/subsystem=undertow/application-security-domain=%s:remove()", deploymentName));
cli.sendLine(String.format("/subsystem=elytron/http-authentication-factory=%s:remove()", elytronName));
cli.sendLine(String.format("/subsystem=elytron/chained-principal-transformer=%s:remove()", transformerName));
domain.remove(cli);
}
}
}
| 13,297
| 56.5671
| 142
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/resteasyclient/ClientConfigProviderBearerTokenTest.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, 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.resteasyclient;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
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.security.common.servlets.SimpleServlet;
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 org.wildfly.security.auth.client.AuthenticationConfiguration;
import org.wildfly.security.auth.client.AuthenticationContext;
import org.wildfly.security.auth.client.MatchRule;
import org.wildfly.security.credential.BearerTokenCredential;
import org.wildfly.test.integration.elytron.util.ClientConfigProviderBearerTokenAbortFilter;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.core.Response;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.net.URL;
@RunAsClient
@RunWith(Arquillian.class)
public class ClientConfigProviderBearerTokenTest {
/**
* Creates WAR with a secured servlet and BASIC authentication configured in web.xml deployment descriptor.
*/
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, ClientConfigProviderBearerTokenTest.class.getSimpleName() + ".war")
.addClasses(SimpleServlet.class);
}
@ArquillianResource
private URL dummyUrl;
/**
* Test that bearer token is loaded from Elytron client config and is used in Authorization header.
* This is done with registered filter that checks Authorization header.
*/
@Test
public void testClientWithBearerToken() {
AuthenticationContext previousAuthContext = AuthenticationContext.getContextManager().getGlobalDefault();
try {
BearerTokenCredential bearerTokenCredential = new BearerTokenCredential("myTestToken");
AuthenticationConfiguration adminConfig = AuthenticationConfiguration.empty().useBearerTokenCredential(bearerTokenCredential);
AuthenticationContext context = AuthenticationContext.empty();
context = context.with(MatchRule.ALL, adminConfig);
AuthenticationContext.getContextManager().setGlobalDefault(context);
context.run(() -> {
ClientBuilder builder = ClientBuilder.newBuilder();
Client client = builder.build();
Response response = client.target(dummyUrl.toString())
.register(ClientConfigProviderBearerTokenAbortFilter.class).request().get();
Assert.assertEquals(SC_OK, response.getStatus());
client.close();
});
} finally {
AuthenticationContext.getContextManager().setGlobalDefault(previousAuthContext);
}
}
/**
* Test that RESTEasy client uses Bearer token auth and not HTTP BASIC if both username with password and bearer token are present in Elytron client config.
* This is done with registered filter that checks Authorization header.
*/
@Test
public void testClientWithBearerTokenAndCredentials() {
AuthenticationContext previousAuthContext = AuthenticationContext.getContextManager().getGlobalDefault();
try {
BearerTokenCredential bearerTokenCredential = new BearerTokenCredential("myTestToken");
AuthenticationConfiguration adminConfig = AuthenticationConfiguration.empty().useName("username").usePassword("password").useBearerTokenCredential(bearerTokenCredential);
AuthenticationContext context = AuthenticationContext.empty();
context = context.with(MatchRule.ALL, adminConfig);
AuthenticationContext.getContextManager().setGlobalDefault(context);
context.run(() -> {
ClientBuilder builder = ClientBuilder.newBuilder();
Client client = builder.build();
Response response = client.target(dummyUrl.toString())
.register(ClientConfigProviderBearerTokenAbortFilter.class).request().get();
Assert.assertEquals(SC_OK, response.getStatus());
client.close();
});
} finally {
AuthenticationContext.getContextManager().setGlobalDefault(previousAuthContext);
}
}
/**
* Test that request does not contain Bearer token if none is retrieved from Elytron client config.
* This is done with registered filter that checks Authorization header.
*/
@Test
public void testClientWithoutBearerToken() {
AuthenticationContext previousAuthContext = AuthenticationContext.getContextManager().getGlobalDefault();
try {
AuthenticationConfiguration adminConfig = AuthenticationConfiguration.empty();
AuthenticationContext context = AuthenticationContext.empty();
context = context.with(MatchRule.ALL, adminConfig);
AuthenticationContext.getContextManager().setGlobalDefault(context);
context.run(() -> {
ClientBuilder builder = ClientBuilder.newBuilder();
Client client = builder.build();
try {
client.target(dummyUrl.toString().toString()).register(ClientConfigProviderBearerTokenAbortFilter.class).request().get();
fail("Configuration not found ex should be thrown.");
} catch (Exception e) {
assertTrue(e.getMessage().contains("The request authorization header is not correct expected:<Bearer myTestToken> but was:<null>"));
} finally {
client.close();
}
});
} finally {
AuthenticationContext.getContextManager().setGlobalDefault(previousAuthContext);
}
}
/**
* Test that request does choose bearer token based on destination of the request.
* This test will fail since bearer token was set on different URL.
*/
@Test
public void testClientChooseCorrectBearerToken() {
AuthenticationContext previousAuthContext = AuthenticationContext.getContextManager().getGlobalDefault();
try {
BearerTokenCredential bearerTokenCredential = new BearerTokenCredential("myTestToken");
AuthenticationConfiguration adminConfig = AuthenticationConfiguration.empty().useBearerTokenCredential(bearerTokenCredential);
AuthenticationContext context = AuthenticationContext.empty();
context = context.with(MatchRule.ALL.matchHost("www.redhat.com"), adminConfig);
AuthenticationContext.getContextManager().setGlobalDefault(context);
context.run(() -> {
ClientBuilder builder = ClientBuilder.newBuilder();
Client client = builder.build();
try {
client.target(dummyUrl.toString()).register(ClientConfigProviderBearerTokenAbortFilter.class).request().get();
fail("Configuration not found ex should be thrown.");
} catch (Exception e) {
assertTrue(e.getMessage().contains("The request authorization header is not correct expected:<Bearer myTestToken> but was:<null>"));
} finally {
client.close();
}
});
} finally {
AuthenticationContext.getContextManager().setGlobalDefault(previousAuthContext);
}
}
/**
* Test that request does choose credentials based on destination of the request.
* Test will succeed since Bearer token was set on requested URL.
*/
@Test
public void testClientChooseCorrectBearerToken2() {
BearerTokenCredential bearerTokenCredential = new BearerTokenCredential("myTestToken");
AuthenticationConfiguration authenticationConfiguration = AuthenticationConfiguration.empty().useBearerTokenCredential(bearerTokenCredential);
AuthenticationContext context = AuthenticationContext.empty();
context = context.with(MatchRule.ALL.matchHost("127.0.0.1"), authenticationConfiguration);
context.run(() -> {
ClientBuilder builder = ClientBuilder.newBuilder();
Client client = builder.build();
Response response = client.target("http://127.0.0.1").register(ClientConfigProviderBearerTokenAbortFilter.class).request().get();
Assert.assertEquals(SC_OK, response.getStatus());
client.close();
});
}
}
| 9,835
| 48.676768
| 182
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/authmode/ConstraintDrivenAuthModeTestCase.java
|
package org.wildfly.test.integration.elytron.authmode;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.auth.BasicScheme;
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.integration.management.util.CLIWrapper;
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.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
import java.net.URI;
import java.net.URL;
import static org.apache.http.HttpStatus.SC_OK;
import static org.apache.http.HttpStatus.SC_UNAUTHORIZED;
import static org.junit.Assert.assertEquals;
@RunAsClient
@RunWith(Arquillian.class)
@ServerSetup(ConstraintDrivenAuthModeTestCase.ServerSetup.class)
public class ConstraintDrivenAuthModeTestCase {
private static final String NAME = ConstraintDrivenAuthModeTestCase.class.getSimpleName();
@Deployment
public static WebArchive createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, NAME + ".war");
war.addAsWebInfResource(ConstraintDrivenAuthModeTestCase.class.getPackage(), "authmode-web.xml", "web.xml");
war.addAsWebResource(ConstraintDrivenAuthModeTestCase.class.getPackage(), "authmode-page.jsp", "secure.jsp");
war.addAsWebResource(ConstraintDrivenAuthModeTestCase.class.getPackage(), "authmode-page.jsp", "unsecure.jsp");
return war;
}
@ArquillianResource
private URL url;
@Test
public void testUnsecuredResourceWithValidCredential() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "unsecure.jsp"));
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password1");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
request.addHeader(new BasicScheme().authenticate(credentials, "UTF-8", false));
try (CloseableHttpClient httpClient = HttpClients.custom()
.build()) {
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "", EntityUtils.toString(response.getEntity()));
}
}
}
@Test
public void testSecuredResourceWithValidCredential() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "secure.jsp"));
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password1");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
request.addHeader(new BasicScheme().authenticate(credentials, "UTF-8", false));
try (CloseableHttpClient httpClient = HttpClients.custom()
.build()) {
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "user1", EntityUtils.toString(response.getEntity()));
}
}
}
@Test
public void testSecuredResourceWithInvalidCredential() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "secure.jsp"));
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password2");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
request.addHeader(new BasicScheme().authenticate(credentials, request));
try (CloseableHttpClient httpClient = HttpClients.custom()
.build()) {
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
}
}
}
@Test
public void testUnsecureResourceWithInvalidCredential() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "unsecure.jsp"));
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password2");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
request.addHeader(new BasicScheme().authenticate(credentials, request));
try (CloseableHttpClient httpClient = HttpClients.custom()
.build()) {
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "", EntityUtils.toString(response.getEntity()));
}
}
}
@Test
public void testUnsecureResourceWithoutCredential() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "unsecure.jsp"));
try (CloseableHttpClient httpClient = HttpClients.custom().build()) {
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "", EntityUtils.toString(response.getEntity()));
}
}
}
static class ServerSetup extends AbstractElytronSetupTask {
@Override
protected ConfigurableElement[] getConfigurableElements() {
ConfigurableElement[] configurableElements = new ConfigurableElement[1];
configurableElements[0] = new ConfigurableElement() {
@Override
public String getName() {
return "Enable CONSTRAINT-DRIVEN auth";
}
@Override
public void create(CLIWrapper cli) throws Exception {
cli.sendLine("/subsystem=undertow/servlet-container=default:write-attribute(name=proactive-authentication, value=false)");
}
@Override
public void remove(CLIWrapper cli) throws Exception {
cli.sendLine("/subsystem=undertow/servlet-container=default:undefine-attribute(name=proactive-authentication)");
}
};
return configurableElements;
}
}
}
| 7,777
| 45.297619
| 142
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/authmode/ProactiveAuthModeTestCase.java
|
package org.wildfly.test.integration.elytron.authmode;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.auth.BasicScheme;
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.integration.management.util.CLIWrapper;
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.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
import java.net.URI;
import java.net.URL;
import static org.apache.http.HttpStatus.SC_OK;
import static org.apache.http.HttpStatus.SC_UNAUTHORIZED;
import static org.junit.Assert.assertEquals;
@RunAsClient
@RunWith(Arquillian.class)
@ServerSetup(ProactiveAuthModeTestCase.ServerSetup.class)
public class ProactiveAuthModeTestCase {
private static final String NAME = ProactiveAuthModeTestCase.class.getSimpleName();
@Deployment
public static WebArchive createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, NAME + ".war");
war.addAsWebInfResource(ProactiveAuthModeTestCase.class.getPackage(), "authmode-web.xml", "web.xml");
war.addAsWebResource(ProactiveAuthModeTestCase.class.getPackage(), "authmode-page.jsp", "secure.jsp");
war.addAsWebResource(ProactiveAuthModeTestCase.class.getPackage(), "authmode-page.jsp", "unsecure.jsp");
return war;
}
@ArquillianResource
private URL url;
@Test
public void testUnsecuredResourceWithValidCredential() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "unsecure.jsp"));
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password1");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
request.addHeader(new BasicScheme().authenticate(credentials, "UTF-8", false));
try (CloseableHttpClient httpClient = HttpClients.custom()
.build()) {
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "user1", EntityUtils.toString(response.getEntity()));
}
}
}
@Test
public void testSecuredResourceWithValidCredential() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "secure.jsp"));
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password1");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
request.addHeader(new BasicScheme().authenticate(credentials, "UTF-8", false));
try (CloseableHttpClient httpClient = HttpClients.custom()
.build()) {
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "user1", EntityUtils.toString(response.getEntity()));
}
}
}
@Test
public void testSecuredResourceWithInvalidCredential() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "secure.jsp"));
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password2");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
request.addHeader(new BasicScheme().authenticate(credentials, request));
try (CloseableHttpClient httpClient = HttpClients.custom()
.build()) {
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
}
}
}
@Test
public void testUnsecureResourceWithInvalidCredential() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "unsecure.jsp"));
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password2");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
request.addHeader(new BasicScheme().authenticate(credentials, request));
try (CloseableHttpClient httpClient = HttpClients.custom()
.build()) {
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
}
}
}
@Test
public void testUnsecureResourceWithoutCredential() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "unsecure.jsp"));
try (CloseableHttpClient httpClient = HttpClients.custom().build()) {
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", "", EntityUtils.toString(response.getEntity()));
}
}
}
static class ServerSetup extends AbstractElytronSetupTask {
@Override
protected ConfigurableElement[] getConfigurableElements() {
ConfigurableElement[] configurableElements = new ConfigurableElement[1];
configurableElements[0] = new ConfigurableElement() {
@Override
public String getName() {
return "Enable CONSTRAINT-DRIVEN auth";
}
@Override
public void create(CLIWrapper cli) throws Exception {
cli.sendLine("/subsystem=undertow/servlet-container=default:write-attribute(name=proactive-authentication, value=true)");
}
@Override
public void remove(CLIWrapper cli) throws Exception {
cli.sendLine("/subsystem=undertow/servlet-container=default:undefine-attribute(name=proactive-authentication)");
}
};
return configurableElements;
}
}
}
| 7,630
| 44.96988
| 141
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ssl/UndertowSslSecurityDomainTestCase.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
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.ssl;
import static jakarta.servlet.http.HttpServletResponse.SC_FORBIDDEN;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
import static org.jboss.as.test.integration.security.common.SSLTruststoreUtil.HTTPS_PORT;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URISyntaxException;
import java.net.URL;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.CloseableHttpClient;
import org.codehaus.plexus.util.FileUtils;
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.controller.client.ModelControllerClient;
import org.jboss.as.test.categories.CommonCriteria;
import org.jboss.as.test.integration.security.common.CoreUtils;
import org.jboss.as.test.integration.security.common.SSLTruststoreUtil;
import org.jboss.as.test.integration.security.common.SecurityTestConstants;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.SimpleServlet;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.test.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ClientCertUndertowDomainMapper;
import org.wildfly.test.security.common.elytron.ConcatenatingPrincipalDecoder;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
import org.wildfly.test.security.common.elytron.ConstantPrincipalDecoder;
import org.wildfly.test.security.common.elytron.CredentialReference;
import org.wildfly.test.security.common.elytron.Path;
import org.wildfly.test.security.common.elytron.PropertyFileAuthzBasedDomain;
import org.wildfly.test.security.common.elytron.SimpleKeyManager;
import org.wildfly.test.security.common.elytron.SimpleKeyStore;
import org.wildfly.test.security.common.elytron.KeyStoreRealm;
import org.wildfly.test.security.common.elytron.SimpleServerSslContext;
import org.wildfly.test.security.common.elytron.SimpleTrustManager;
import org.wildfly.test.security.common.elytron.X500AttributePrincipalDecoder;
import org.wildfly.test.security.common.elytron.UndertowSslContext;
import org.wildfly.test.security.common.elytron.UserWithAttributeValues;
/**
* Smoke tests for certificate based authentication using Elytron server-ssl-context, security domain,
* and key store realm.
*
* This test case is preparation and temporary replacement for
* testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/security/cert/WebSecurityCERTTestCase.java
* before making it work with Elytron.
*
* @author Ondrej Kotek
*/
@RunWith(Arquillian.class)
@ServerSetup({ UndertowSslSecurityDomainTestCase.ElytronSslContextInUndertowSetupTask.class })
@RunAsClient
@Category(CommonCriteria.class)
public class UndertowSslSecurityDomainTestCase {
private static final String NAME = UndertowSslSecurityDomainTestCase.class.getSimpleName();
private static final File WORK_DIR = new File("target" + File.separatorChar + NAME);
private static final File SERVER_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.SERVER_KEYSTORE);
private static final File SERVER_TRUSTSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.SERVER_TRUSTSTORE);
private static final File CLIENT_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.CLIENT_KEYSTORE);
private static final File CLIENT_TRUSTSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.CLIENT_TRUSTSTORE);
private static final File UNTRUSTED_STORE_FILE = new File(WORK_DIR, SecurityTestConstants.UNTRUSTED_KEYSTORE);
private static final String PASSWORD = SecurityTestConstants.KEYSTORE_PASSWORD;
private static URL securedUrl;
private static URL securedUrlRole1;
private static URL securedUrlRole2;
/**
* Creates WAR with a secured servlet and CLIENT-CERT authentication configured in web.xml deployment descriptor.
*/
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, NAME + ".war")
.addClass(SimpleServlet.class)
.addAsWebInfResource(UndertowSslSecurityDomainTestCase.class.getPackage(), NAME + "-web.xml", "web.xml")
.addAsWebInfResource(UndertowSslSecurityDomainTestCase.class.getPackage(), NAME + "-jboss-web.xml", "jboss-web.xml");
}
@BeforeClass
public static void setSecuredRootUrl() throws Exception {
try {
securedUrl = new URL("https", TestSuiteEnvironment.getServerAddress(), HTTPS_PORT, "/" + NAME + "/");
securedUrlRole1 = new URL("https", TestSuiteEnvironment.getServerAddress(), HTTPS_PORT, "/" + NAME + "/role1");
securedUrlRole2 = new URL("https", TestSuiteEnvironment.getServerAddress(), HTTPS_PORT, "/" + NAME + "/role2");
} catch (MalformedURLException ex) {
throw new IllegalStateException("Unable to create HTTPS URL to server root", ex);
}
}
/**
* Tests access to resource that does not require authentication.
*/
@Test
public void testUnprotectedAccess() {
HttpClient client = SSLTruststoreUtil
.getHttpClientWithSSL(CLIENT_KEYSTORE_FILE, PASSWORD, CLIENT_TRUSTSTORE_FILE, PASSWORD);
assertUnprotectedAccess(client);
closeClient(client);
}
/**
* Tests access to resource that requires authentication and authorization.
*/
@Test
public void testProtectedAccess() {
HttpClient client = SSLTruststoreUtil
.getHttpClientWithSSL(CLIENT_KEYSTORE_FILE, PASSWORD, CLIENT_TRUSTSTORE_FILE, PASSWORD);
assertProtectedAccess(client, SC_OK);
closeClient(client);
}
/**
* Tests access to resource that requires authentication and authorization. Principal has not required role.
*/
@Test
public void testForbidden() {
HttpClient client = SSLTruststoreUtil
.getHttpClientWithSSL(CLIENT_KEYSTORE_FILE, PASSWORD, CLIENT_TRUSTSTORE_FILE, PASSWORD);
assertAccessForbidden(client);
closeClient(client);
}
/**
* Tests access to resource that requires authentication and authorization. Client has not trusted certificate.
*/
@Test
public void testUntrustedCertificate() {
HttpClient client = SSLTruststoreUtil
.getHttpClientWithSSL(UNTRUSTED_STORE_FILE, PASSWORD, CLIENT_TRUSTSTORE_FILE, PASSWORD);
assertSslHandshakeFails(client);
closeClient(client);
}
private void assertSslHandshakeFails(HttpClient client) {
try {
Utils.makeCallWithHttpClient(securedUrlRole1, client, SC_OK);
} catch (SSLHandshakeException | SocketException e) {
// expected
return;
} catch (SSLException e) {
if (e.getCause() instanceof SocketException) return; // expected
throw new IllegalStateException("Unexpected SSLException", e);
} catch (IOException | URISyntaxException ex) {
throw new IllegalStateException("Unable to request server root over HTTPS", ex);
}
fail("SSL handshake should fail");
}
private void assertUnprotectedAccess(HttpClient client) {
try {
Utils.makeCallWithHttpClient(securedUrl, client, SC_OK);
} catch (IOException | URISyntaxException ex) {
throw new IllegalStateException("Unable to request " + securedUrl.toExternalForm(), ex);
}
}
private void assertProtectedAccess(HttpClient client, int expectedStatusCode) {
try {
Utils.makeCallWithHttpClient(securedUrlRole1, client, expectedStatusCode);
} catch (IOException | URISyntaxException ex) {
throw new IllegalStateException("Unable to request " + securedUrlRole1.toExternalForm(), ex);
}
}
private void assertAccessForbidden(HttpClient client) {
try {
Utils.makeCallWithHttpClient(securedUrlRole2, client, SC_FORBIDDEN);
} catch (IOException | URISyntaxException ex) {
throw new IllegalStateException("Unable to request " + securedUrlRole2.toExternalForm(), ex);
}
}
private void closeClient(HttpClient client) {
try {
((CloseableHttpClient) client).close();
} catch (IOException ex) {
throw new IllegalStateException("Unable to close HTTP client", ex);
}
}
/**
* Creates Elytron server-ssl-context and key/trust stores.
*/
static class ElytronSslContextInUndertowSetupTask extends AbstractElytronSetupTask {
@Override
protected void setup(final ModelControllerClient modelControllerClient) throws Exception {
keyMaterialSetup(WORK_DIR);
super.setup(modelControllerClient);
}
@Override
protected ConfigurableElement[] getConfigurableElements() {
return new ConfigurableElement[] {
SimpleKeyStore.builder().withName(NAME + SecurityTestConstants.SERVER_KEYSTORE)
.withPath(Path.builder().withPath(SERVER_KEYSTORE_FILE.getPath()).build())
.withCredentialReference(CredentialReference.builder().withClearText(PASSWORD).build())
.build(),
SimpleKeyStore.builder().withName(NAME + SecurityTestConstants.SERVER_TRUSTSTORE)
.withPath(Path.builder().withPath(SERVER_TRUSTSTORE_FILE.getPath()).build())
.withCredentialReference(CredentialReference.builder().withClearText(PASSWORD).build())
.build(),
SimpleKeyManager.builder().withName(NAME)
.withKeyStore(NAME + SecurityTestConstants.SERVER_KEYSTORE)
.withCredentialReference(CredentialReference.builder().withClearText(PASSWORD).build())
.build(),
SimpleTrustManager.builder().withName(NAME)
.withKeyStore(NAME + SecurityTestConstants.SERVER_TRUSTSTORE)
.build(),
KeyStoreRealm.builder().withName(NAME)
.withKeyStore(NAME + SecurityTestConstants.SERVER_TRUSTSTORE)
.build(),
ConstantPrincipalDecoder.builder().withName(NAME + "constant").withConstant("CN").build(),
X500AttributePrincipalDecoder.builder().withName(NAME + "X500")
.withOid("2.5.4.3")
.withMaximumSegments(1)
.build(),
ConcatenatingPrincipalDecoder.builder().withName(NAME)
.withJoiner("=")
.withDecoders(NAME + "constant", NAME + "X500")
.build(),
PropertyFileAuthzBasedDomain.builder().withName(NAME)
.withAuthnRealm(NAME)
.withPrincipalDecoder(NAME)
.withUser(UserWithAttributeValues.builder().withName("CN=client").withValues("Role1").build())
.build(),
ClientCertUndertowDomainMapper.builder().withName(NAME).withSecurityDomain(NAME).build(),
SimpleServerSslContext.builder().withName(NAME)
.withKeyManagers(NAME)
.withTrustManagers(NAME)
.withSecurityDomain(NAME)
.withAuthenticationOptional(true)
.withNeedClientAuth(true) // test that the handshake fails if the client certificate is not trusted
.build(),
UndertowSslContext.builder().withName(NAME).build()
};
}
@Override
protected void tearDown(ModelControllerClient modelControllerClient) throws Exception {
super.tearDown(modelControllerClient);
FileUtils.deleteDirectory(WORK_DIR);
}
protected static void keyMaterialSetup(File workDir) throws Exception {
FileUtils.deleteDirectory(workDir);
workDir.mkdirs();
Assert.assertTrue(workDir.exists());
Assert.assertTrue(workDir.isDirectory());
CoreUtils.createKeyMaterial(workDir);
}
}
}
| 13,963
| 46.496599
| 133
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ssl/UndertowTwoWaySslTestCase.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
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.ssl;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
import static org.jboss.as.test.integration.security.common.SSLTruststoreUtil.HTTPS_PORT;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.CloseableHttpClient;
import org.codehaus.plexus.util.FileUtils;
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.controller.client.ModelControllerClient;
import org.jboss.as.test.integration.security.common.CoreUtils;
import org.jboss.as.test.integration.security.common.SSLTruststoreUtil;
import org.jboss.as.test.integration.security.common.SecurityTestConstants;
import org.jboss.as.test.integration.security.common.Utils;
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.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.test.integration.elytron.util.WelcomeContent;
import org.wildfly.test.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
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.elytron.SimpleTrustManager;
import org.wildfly.test.security.common.elytron.UndertowSslContext;
/**
* Smoke test for two way SSL connection with Undertow HTTPS listener backed by Elytron server-ssl-context with default
* settings (client certificate is not required).
*
* In case the client certificate is not trusted or present, the request should be successful.
*
* @author Ondrej Kotek
*/
@RunWith(Arquillian.class)
@ServerSetup({ UndertowTwoWaySslTestCase.ElytronSslContextInUndertowSetupTask.class, WelcomeContent.SetupTask.class })
@RunAsClient
public class UndertowTwoWaySslTestCase {
private static final String NAME = UndertowTwoWaySslTestCase.class.getSimpleName();
private static final File WORK_DIR = new File("target" + File.separatorChar + NAME);
private static final File SERVER_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.SERVER_KEYSTORE);
private static final File SERVER_TRUSTSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.SERVER_TRUSTSTORE);
private static final File CLIENT_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.CLIENT_KEYSTORE);
private static final File CLIENT_TRUSTSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.CLIENT_TRUSTSTORE);
private static final File UNTRUSTED_STORE_FILE = new File(WORK_DIR, SecurityTestConstants.UNTRUSTED_KEYSTORE);
private static final String PASSWORD = SecurityTestConstants.KEYSTORE_PASSWORD;
private static URL securedRootUrl;
// just to make server setup task work
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, NAME + ".war")
.add(new StringAsset("index page"), "index.html");
}
@BeforeClass
public static void setSecuredRootUrl() throws Exception {
try {
securedRootUrl = new URL("https", TestSuiteEnvironment.getServerAddress(), HTTPS_PORT, "");
} catch (MalformedURLException ex) {
throw new IllegalStateException("Unable to create HTTPS URL to server root", ex);
}
}
@Test
public void testSendingTrustedClientCertificate() {
HttpClient client = SSLTruststoreUtil
.getHttpClientWithSSL(CLIENT_KEYSTORE_FILE, PASSWORD, CLIENT_TRUSTSTORE_FILE, PASSWORD);
assertConnectionToServer(client, SC_OK);
closeClient(client);
}
@Test
public void testSendingNonTrustedClientCertificate() {
HttpClient client = SSLTruststoreUtil
.getHttpClientWithSSL(UNTRUSTED_STORE_FILE, PASSWORD, CLIENT_TRUSTSTORE_FILE, PASSWORD);
assertConnectionToServer(client, SC_OK);
closeClient(client);
}
@Test
public void testSendingNoClientCertificate() {
HttpClient client = SSLTruststoreUtil.getHttpClientWithSSL(CLIENT_TRUSTSTORE_FILE, PASSWORD);
assertConnectionToServer(client, SC_OK);
closeClient(client);
}
private void assertConnectionToServer(HttpClient client, int expectedStatusCode) {
try {
Utils.makeCallWithHttpClient(securedRootUrl, client, expectedStatusCode);
} catch (IOException | URISyntaxException ex) {
throw new IllegalStateException("Unable to request server root over HTTPS", ex);
}
}
private void closeClient(HttpClient client) {
try {
((CloseableHttpClient) client).close();
} catch (IOException ex) {
throw new IllegalStateException("Unable to close HTTP client", ex);
}
}
/**
* Creates Elytron server-ssl-context and key/trust stores.
*/
static class ElytronSslContextInUndertowSetupTask extends AbstractElytronSetupTask {
@Override
protected void setup(final ModelControllerClient modelControllerClient) throws Exception {
keyMaterialSetup(WORK_DIR);
super.setup(modelControllerClient);
}
@Override
protected ConfigurableElement[] getConfigurableElements() {
return new ConfigurableElement[] {
SimpleKeyStore.builder().withName(NAME + SecurityTestConstants.SERVER_KEYSTORE)
.withPath(Path.builder().withPath(SERVER_KEYSTORE_FILE.getPath()).build())
.withCredentialReference(CredentialReference.builder().withClearText(PASSWORD).build())
.build(),
SimpleKeyStore.builder().withName(NAME + SecurityTestConstants.SERVER_TRUSTSTORE)
.withPath(Path.builder().withPath(SERVER_TRUSTSTORE_FILE.getPath()).build())
.withCredentialReference(CredentialReference.builder().withClearText(PASSWORD).build())
.build(),
SimpleKeyManager.builder().withName(NAME)
.withKeyStore(NAME + SecurityTestConstants.SERVER_KEYSTORE)
.withCredentialReference(CredentialReference.builder().withClearText(PASSWORD).build())
.build(),
SimpleTrustManager.builder().withName(NAME)
.withKeyStore(NAME + SecurityTestConstants.SERVER_TRUSTSTORE)
.build(),
SimpleServerSslContext.builder().withName(NAME).withKeyManagers(NAME).withTrustManagers(NAME).build(),
UndertowSslContext.builder().withName(NAME).build()
};
}
@Override
protected void tearDown(ModelControllerClient modelControllerClient) throws Exception {
super.tearDown(modelControllerClient);
FileUtils.deleteDirectory(WORK_DIR);
}
protected static void keyMaterialSetup(File workDir) throws Exception {
FileUtils.deleteDirectory(workDir);
workDir.mkdirs();
Assert.assertTrue(workDir.exists());
Assert.assertTrue(workDir.isDirectory());
CoreUtils.createKeyMaterial(workDir);
}
}
}
| 8,925
| 45.489583
| 119
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ssl/UndertowSSLv2HelloTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, 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.ssl;
import static java.security.AccessController.doPrivileged;
import static org.jboss.as.test.integration.security.common.SSLTruststoreUtil.HTTPS_PORT;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.PrivilegedAction;
import java.security.Security;
import jakarta.ws.rs.ProcessingException;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.core.Response;
import org.codehaus.plexus.util.FileUtils;
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.controller.client.ModelControllerClient;
import org.jboss.as.test.integration.management.util.CLIWrapper;
import org.jboss.as.test.integration.security.common.CoreUtils;
import org.jboss.as.test.integration.security.common.SecurityTestConstants;
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.AfterClass;
import org.junit.Assert;
import org.junit.AssumptionViolatedException;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runners.model.Statement;
import org.wildfly.security.auth.client.AuthenticationContext;
import org.wildfly.security.auth.client.ElytronXmlParser;
import org.wildfly.security.auth.client.InvalidAuthenticationConfigurationException;
import org.wildfly.test.integration.elytron.util.WelcomeContent;
import org.wildfly.test.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
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.elytron.SimpleTrustManager;
/**
* Smoke test for two way SSL connection with Undertow HTTPS listener backed by Elytron
* server-ssl-context
* with need-client-auth=true (client certificate is required) using SSLv2Hello.
*
* In case the client certificate is not trusted or present, the SSL handshake should fail.
*
* Additionally, smoke test for one way SSL connection with Undertow HTTPS listener
* backed by Elytron server-ssl-context.
*
* @author Ondrej Kotek
* @author Sonia Zaldana
*/
@RunWith(Arquillian.class)
@ServerSetup({ UndertowSSLv2HelloTestCase.ElytronSslContextInUndertowSetupTask.class, WelcomeContent.SetupTask.class})
@RunAsClient
public class UndertowSSLv2HelloTestCase {
private static final String NAME = UndertowTwoWaySslNeedClientAuthTestCase.class.getSimpleName();
private static final File WORK_DIR = new File("target" + File.separatorChar + NAME);
private static final File SERVER_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.SERVER_KEYSTORE);
private static final File SERVER_TRUSTSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.SERVER_TRUSTSTORE);
private static final String PASSWORD = SecurityTestConstants.KEYSTORE_PASSWORD;
private static final String SSLV2HELLO_CONTEXT = "SSLv2HelloContext";
private static final String DEFAULT_CONTEXT = "DefaultContext";
private static final String SSLV2HELLO_CONTEXT_ONE_WAY = "SSLv2HelloContextOneWay";
private static final String HTTPS = "https";
private static URL securedRootUrl;
public static String disabledAlgorithms;
@ClassRule
public static IbmVerification ibmVerification =
new IbmVerification(TestSuiteEnvironment.isIbmJvm());
// just to make server setup task work
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, NAME + ".war")
.add(new StringAsset("index page"), "index.html");
}
@BeforeClass
public static void setUp() {
disabledAlgorithms = Security.getProperty("jdk.tls.disabledAlgorithms");
if (disabledAlgorithms != null && (disabledAlgorithms.contains("TLSv1") || disabledAlgorithms.contains("TLSv1.1"))) {
// reset the disabled algorithms to make sure that the protocols required in this test are available
Security.setProperty("jdk.tls.disabledAlgorithms", "");
}
try {
securedRootUrl = new URL("https", TestSuiteEnvironment.getServerAddress(), HTTPS_PORT, "");
} catch (MalformedURLException ex) {
throw new IllegalStateException("Unable to create HTTPS URL to server root", ex);
}
}
@AfterClass
public static void cleanUp() {
if (disabledAlgorithms != null) {
Security.setProperty("jdk.tls.disabledAlgorithms", disabledAlgorithms);
}
}
/**
* One way SSL - RESTEasy client sends SSLv2Hello message and server supports the protocol.
* Handshake should succeed.
*/
@Test
public void testOneWayElytronClientServerSupportsSSLv2Hello() throws Exception {
configureSSLContext(SSLV2HELLO_CONTEXT_ONE_WAY);
AuthenticationContext context = doPrivileged((PrivilegedAction<AuthenticationContext>) () -> {
try {
URL config = getClass().getResource("wildfly-config-one-way-sslv2hello.xml");
return ElytronXmlParser.parseAuthenticationClientConfiguration(config.toURI()).create();
} catch (Throwable t) {
throw new InvalidAuthenticationConfigurationException(t);
}
});
context.run(() -> {
ClientBuilder clientBuilder = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true);
Client client = clientBuilder.build();
Response response = client.target(String.valueOf(securedRootUrl)).request().get();
Assert.assertEquals(200, response.getStatus());
});
restoreConfiguration();
}
/**
* Two way SSL - RESTEasy client sends SSLv2Hello message and server supports the protocol.
* Handshake should succeed.
*/
@Test
public void testTwoWayElytronClientServerSupportsSSLv2Hello() throws Exception {
configureSSLContext(SSLV2HELLO_CONTEXT);
AuthenticationContext context = doPrivileged((PrivilegedAction<AuthenticationContext>) () -> {
try {
URL config = getClass().getResource("wildfly-config-sslv2hello.xml");
return ElytronXmlParser.parseAuthenticationClientConfiguration(config.toURI()).create();
} catch (Throwable t) {
throw new InvalidAuthenticationConfigurationException(t);
}
});
context.run(() -> {
ClientBuilder clientBuilder = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true);
Client client = clientBuilder.build();
Response response = client.target(String.valueOf(securedRootUrl)).request().get();
Assert.assertEquals(200, response.getStatus());
});
restoreConfiguration();
}
/**
* Two way SSL - Server supports SSLv2Hello, but client does not support SSLv2Hello.
* Handshake should succeed as they still share protocol TLSv1 in common.
*/
@Test
public void testTwoWayElytronClientNoSSLv2HelloSupport() throws Exception {
configureSSLContext(SSLV2HELLO_CONTEXT);
AuthenticationContext context = doPrivileged((PrivilegedAction<AuthenticationContext>) () -> {
try {
URL config = getClass().getResource("wildfly-config-no-sslv2hello.xml");
return ElytronXmlParser.parseAuthenticationClientConfiguration(config.toURI()).create();
} catch (Throwable t) {
throw new InvalidAuthenticationConfigurationException(t);
}
});
context.run(() -> {
ClientBuilder clientBuilder = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true);
Client client = clientBuilder.build();
Response response = client.target(String.valueOf(securedRootUrl)).request().get();
Assert.assertEquals(200, response.getStatus());
});
restoreConfiguration();
}
/**
* Two way SSL - Server does not support SSLv2Hello, but client sends SSLv2Hello message.
* Handshake should fail.
*/
@Test(expected = ProcessingException.class)
public void testTwoWayElytronServerNoSSLv2HelloSupport() throws Exception {
configureSSLContext(DEFAULT_CONTEXT);
AuthenticationContext context = doPrivileged((PrivilegedAction<AuthenticationContext>) () -> {
try {
URL config = getClass().getResource("wildfly-config-sslv2hello.xml");
return ElytronXmlParser.parseAuthenticationClientConfiguration(config.toURI()).create();
} catch (Throwable t) {
throw new InvalidAuthenticationConfigurationException(t);
}
});
context.run(() -> {
ClientBuilder clientBuilder = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true);
Client client = clientBuilder.build();
Response response = client.target(String.valueOf(securedRootUrl)).request().get();
Assert.assertEquals(200, response.getStatus());
});
restoreConfiguration();
}
/**
* Two Way SSL - Client and Server don't support SSLv2Hello as it has not been explicitly configured.
* They each have their default configuration. Handshake should succeed.
*/
@Test
public void testTwoWayElytronServerClientDefaultConfig() throws Exception {
configureSSLContext(DEFAULT_CONTEXT);
AuthenticationContext context = doPrivileged((PrivilegedAction<AuthenticationContext>) () -> {
try {
URL config = getClass().getResource("wildfly-config-no-sslv2hello.xml");
return ElytronXmlParser.parseAuthenticationClientConfiguration(config.toURI()).create();
} catch (Throwable t) {
throw new InvalidAuthenticationConfigurationException(t);
}
});
context.run(() -> {
ClientBuilder clientBuilder = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true);
Client client = clientBuilder.build();
Response response = client.target(String.valueOf(securedRootUrl)).request().get();
Assert.assertEquals(200, response.getStatus());
});
restoreConfiguration();
}
private void configureSSLContext(String sslContextName) throws Exception {
try(CLIWrapper cli = new CLIWrapper(true)) {
cli.sendLine("batch");
cli.sendLine(String.format("/subsystem=undertow/server=default-server/https-listener=%s:write-attribute" +
"(name=ssl-context,value=%s)", HTTPS, sslContextName));
cli.sendLine("run-batch");
cli.sendLine("reload");
}
}
private void restoreConfiguration() throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
cli.sendLine("batch");
cli.sendLine(String.format("/subsystem=undertow/server=default-server/https-listener=%s:write-attribute" +
"(name=ssl-context,value=%s)", HTTPS, "applicationSSC"));
cli.sendLine("run-batch");
cli.sendLine("reload");
}
}
public static class IbmVerification implements TestRule {
private boolean isIbm;
public IbmVerification(boolean isIbm) {
this.isIbm = isIbm;
}
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
if (isIbm) {
throw new AssumptionViolatedException("IBM JDK does not support SSLv2Hello. Skipping test!");
} else {
base.evaluate();
}
}
};
}
}
/**
* Creates Elytron server-ssl-context and key/trust stores.
*/
static class ElytronSslContextInUndertowSetupTask extends AbstractElytronSetupTask {
@Override
protected void setup(final ModelControllerClient modelControllerClient) throws Exception {
keyMaterialSetup(WORK_DIR);
super.setup(modelControllerClient);
}
@Override
protected ConfigurableElement[] getConfigurableElements() {
return new ConfigurableElement[] {
SimpleKeyStore.builder().withName(NAME + SecurityTestConstants.SERVER_KEYSTORE)
.withPath(Path.builder().withPath(SERVER_KEYSTORE_FILE.getPath()).build())
.withCredentialReference(CredentialReference.builder().withClearText(PASSWORD).build())
.build(),
SimpleKeyStore.builder().withName(NAME + SecurityTestConstants.SERVER_TRUSTSTORE)
.withPath(Path.builder().withPath(SERVER_TRUSTSTORE_FILE.getPath()).build())
.withCredentialReference(CredentialReference.builder().withClearText(PASSWORD).build())
.build(),
SimpleKeyManager.builder().withName(NAME)
.withKeyStore(NAME + SecurityTestConstants.SERVER_KEYSTORE)
.withCredentialReference(CredentialReference.builder().withClearText(PASSWORD).build())
.build(),
SimpleTrustManager.builder().withName(NAME)
.withKeyStore(NAME + SecurityTestConstants.SERVER_TRUSTSTORE)
.build(),
SimpleServerSslContext.builder().withName(SSLV2HELLO_CONTEXT)
.withKeyManagers(NAME)
.withTrustManagers(NAME)
.withNeedClientAuth(true)
.withProtocols("SSLv2Hello", "TLSv1")
.build(),
SimpleServerSslContext.builder().withName(DEFAULT_CONTEXT)
.withKeyManagers(NAME)
.withTrustManagers(NAME)
.withNeedClientAuth(true)
.build(),
SimpleServerSslContext.builder().withName(SSLV2HELLO_CONTEXT_ONE_WAY)
.withKeyManagers(NAME)
.withProtocols("SSLv2Hello", "TLSv1")
.build()
};
}
@Override
protected void tearDown(ModelControllerClient modelControllerClient) throws Exception {
super.tearDown(modelControllerClient);
FileUtils.deleteDirectory(WORK_DIR);
}
protected static void keyMaterialSetup(File workDir) throws Exception {
FileUtils.deleteDirectory(workDir);
workDir.mkdirs();
Assert.assertTrue(workDir.exists());
Assert.assertTrue(workDir.isDirectory());
CoreUtils.createKeyMaterial(workDir);
}
}
}
| 16,806
| 44.424324
| 125
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ssl/AutomaticSelfSignedCertificateNotGeneratedTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, 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.ssl;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
import static org.jboss.as.test.integration.security.common.SSLTruststoreUtil.HTTPS_PORT;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.security.auth.x500.X500Principal;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.CloseableHttpClient;
import org.codehaus.plexus.util.FileUtils;
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.controller.client.ModelControllerClient;
import org.jboss.as.test.categories.CommonCriteria;
import org.jboss.as.test.integration.management.util.CLIWrapper;
import org.jboss.as.test.integration.security.common.SSLTruststoreUtil;
import org.jboss.as.test.integration.security.common.SecurityTestConstants;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.SimpleServlet;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.security.x500.cert.SelfSignedX509CertificateAndSigningKey;
import org.wildfly.test.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
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.elytron.UndertowSslContext;
/**
* Test that a self-signed certificate is not automatically generated if the keystore
* file already exists.
*
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@RunWith(Arquillian.class)
@ServerSetup({ AutomaticSelfSignedCertificateNotGeneratedTestCase.ElytronAndUndertowSetupTask.class })
@RunAsClient
@Category(CommonCriteria.class)
public class AutomaticSelfSignedCertificateNotGeneratedTestCase {
private static final String NAME = AutomaticSelfSignedCertificateNotGeneratedTestCase.class.getSimpleName();
private static final File WORK_DIR = new File("target" + File.separatorChar + NAME);
private static final File SERVER_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.SERVER_KEYSTORE);
private static final File CLIENT_TRUSTSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.CLIENT_TRUSTSTORE);
private static final String PASSWORD = SecurityTestConstants.KEYSTORE_PASSWORD;
private static final String GENERATE_SELF_SIGNED_CERTIFICATE_HOST="customHostName";
private static final String SERVER_ALIAS = "server";
private static final String EXISTING_HOST = "existingHost";
private static final byte[] IV = {
0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,
0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20
};
private static final byte[] SALT = {
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08
};
private static final int ITERATION_COUNT = 1024;
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, NAME + ".war").addClasses(SimpleServlet.class);
}
@Test
public void testSelfSignedCertificateNotGeneratedIfKeyStoreFileExists() throws Exception {
assertTrue(SERVER_KEYSTORE_FILE.exists());
assertTrue(CLIENT_TRUSTSTORE_FILE.exists());
final URL servletUrl = new URL("https", TestSuiteEnvironment.getServerAddress(), HTTPS_PORT,
"/" + NAME + "/" + SimpleServlet.SERVLET_PATH.substring(1));
HttpClient client = SSLTruststoreUtil.getHttpClientWithSSL(CLIENT_TRUSTSTORE_FILE, PASSWORD, "PKCS12");
try {
Utils.makeCallWithHttpClient(servletUrl, client, SC_OK);
try (FileInputStream is = new FileInputStream(SERVER_KEYSTORE_FILE.getAbsolutePath())) {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(is, PASSWORD.toCharArray());
assertEquals(1, keyStore.size());
X509Certificate serverCert = (X509Certificate) keyStore.getCertificate(SERVER_ALIAS);
assertEquals("CN=" + EXISTING_HOST, serverCert.getSubjectX500Principal().getName());
}
} catch (IOException | URISyntaxException ex) {
throw new IllegalStateException("Unable to request server root over HTTPS", ex);
} finally {
closeClient(client);
}
}
@Test
public void testSelfSignedCertificateNotGeneratedWithGenerateAttributeUndefined() throws Exception {
// undefine generate-self-signed-certificate-host
try (CLIWrapper cli = new CLIWrapper(true)) {
cli.sendLine(String.format("/subsystem=elytron/key-manager=%s:undefine-attribute(name=generate-self-signed-certificate-host)",
NAME));
cli.sendLine(String.format("reload"));
}
try {
assertTrue(SERVER_KEYSTORE_FILE.exists());
assertTrue(CLIENT_TRUSTSTORE_FILE.exists());
final URL servletUrl = new URL("https", TestSuiteEnvironment.getServerAddress(), HTTPS_PORT,
"/" + NAME + "/" + SimpleServlet.SERVLET_PATH.substring(1));
HttpClient client = SSLTruststoreUtil.getHttpClientWithSSL(CLIENT_TRUSTSTORE_FILE, PASSWORD, "PKCS12");
try {
Utils.makeCallWithHttpClient(servletUrl, client, SC_OK);
try (FileInputStream is = new FileInputStream(SERVER_KEYSTORE_FILE.getAbsolutePath())) {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(is, PASSWORD.toCharArray());
assertEquals(1, keyStore.size());
X509Certificate serverCert = (X509Certificate) keyStore.getCertificate(SERVER_ALIAS);
assertEquals("CN=" + EXISTING_HOST, serverCert.getSubjectX500Principal().getName());
}
} catch (IOException | URISyntaxException ex) {
throw new IllegalStateException("Unable to request server root over HTTPS", ex);
} finally {
closeClient(client);
}
} finally {
// clean up
try (CLIWrapper cli = new CLIWrapper(true)) {
cli.sendLine(String.format("/subsystem=elytron/key-manager=%s:write-attribute(name=generate-self-signed-certificate-host,value=%s)",
NAME, GENERATE_SELF_SIGNED_CERTIFICATE_HOST));
cli.sendLine(String.format("reload"));
}
}
}
static class ElytronAndUndertowSetupTask extends AbstractElytronSetupTask {
@Override
protected void setup(final ModelControllerClient modelControllerClient) throws Exception {
createServerKeyStoreAndClientTrustStore();
super.setup(modelControllerClient);
}
@Override
protected ConfigurableElement[] getConfigurableElements() {
return new ConfigurableElement[] {
SimpleKeyStore.builder().withName(NAME + SecurityTestConstants.SERVER_KEYSTORE)
.withPath(Path.builder().withPath(SERVER_KEYSTORE_FILE.getAbsolutePath()).build())
.withCredentialReference(CredentialReference.builder().withClearText(PASSWORD).build())
.withType("PKCS12")
.build(),
SimpleKeyManager.builder().withName(NAME)
.withKeyStore(NAME + SecurityTestConstants.SERVER_KEYSTORE)
.withCredentialReference(CredentialReference.builder().withClearText(PASSWORD).build())
.withGenerateSelfSignedCertificateHost(GENERATE_SELF_SIGNED_CERTIFICATE_HOST)
.build(),
SimpleServerSslContext.builder().withName(NAME)
.withKeyManagers(NAME)
.build(),
UndertowSslContext.builder().withName(NAME).build()
};
}
@Override
protected void tearDown(ModelControllerClient modelControllerClient) throws Exception {
super.tearDown(modelControllerClient);
FileUtils.deleteDirectory(WORK_DIR);
}
private void createServerKeyStoreAndClientTrustStore() throws Exception {
if (WORK_DIR.exists()) {
FileUtils.deleteDirectory(WORK_DIR);
}
WORK_DIR.mkdirs();
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(null, null);
SelfSignedX509CertificateAndSigningKey selfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey.builder()
.setDn(new X500Principal("CN=existingHost"))
.setKeyAlgorithmName("RSA")
.setSignatureAlgorithmName("SHA256withRSA")
.build();
PrivateKey privateKey = selfSignedX509CertificateAndSigningKey.getSigningKey();
X509Certificate serverCert = selfSignedX509CertificateAndSigningKey.getSelfSignedCertificate();
KeyStore.Entry entry = new KeyStore.PrivateKeyEntry(privateKey, new X509Certificate[]{ serverCert });
KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(PASSWORD.toCharArray(), "PBEWithHmacSHA256AndAES_128",
new PBEParameterSpec(SALT, ITERATION_COUNT, new IvParameterSpec(IV)));
ks.setEntry("server", entry, passwordProtection);
try (FileOutputStream fos = new FileOutputStream(SERVER_KEYSTORE_FILE)) {
ks.store(fos, PASSWORD.toCharArray());
}
try (FileOutputStream fos = new FileOutputStream(CLIENT_TRUSTSTORE_FILE)) {
KeyStore trustStore = KeyStore.getInstance("PKCS12");
trustStore.load(null, null);
trustStore.setCertificateEntry("server", serverCert);
trustStore.store(fos, PASSWORD.toCharArray());
}
}
}
private void closeClient(HttpClient client) {
try {
((CloseableHttpClient) client).close();
} catch (IOException ex) {
throw new IllegalStateException("Unable to close HTTP client", ex);
}
}
}
| 12,273
| 49.510288
| 148
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ssl/UndertowTwoWaySslNeedClientAuthTestCase.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
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.ssl;
import static java.security.AccessController.doPrivileged;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
import static org.jboss.as.test.integration.security.common.SSLTruststoreUtil.HTTPS_PORT;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.AccessController;
import java.security.GeneralSecurityException;
import java.security.PrivilegedAction;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import jakarta.ws.rs.ProcessingException;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.core.Response;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.CloseableHttpClient;
import org.codehaus.plexus.util.FileUtils;
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.controller.client.ModelControllerClient;
import org.jboss.as.test.integration.security.common.CoreUtils;
import org.jboss.as.test.integration.security.common.SSLTruststoreUtil;
import org.jboss.as.test.integration.security.common.SecurityTestConstants;
import org.jboss.as.test.integration.security.common.Utils;
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.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.security.auth.client.AuthenticationContext;
import org.wildfly.security.auth.client.AuthenticationContextConfigurationClient;
import org.wildfly.security.auth.client.ElytronXmlParser;
import org.wildfly.security.auth.client.InvalidAuthenticationConfigurationException;
import org.wildfly.test.integration.elytron.util.WelcomeContent;
import org.wildfly.test.integration.elytron.util.HttpAuthorization;
import org.wildfly.test.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
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.elytron.SimpleTrustManager;
import org.wildfly.test.security.common.elytron.UndertowSslContext;
/**
* Smoke test for two way SSL connection with Undertow HTTPS listener backed by Elytron server-ssl-context
* with need-client-auth=true (client certificate is required).
*
* In case the client certificate is not trusted or present, the SSL handshake should fail.
*
* @author Ondrej Kotek
*/
@RunWith(Arquillian.class)
@ServerSetup({ UndertowTwoWaySslNeedClientAuthTestCase.ElytronSslContextInUndertowSetupTask.class, WelcomeContent.SetupTask.class })
@RunAsClient
public class UndertowTwoWaySslNeedClientAuthTestCase {
private static final String NAME = UndertowTwoWaySslNeedClientAuthTestCase.class.getSimpleName();
private static final File WORK_DIR = new File("target" + File.separatorChar + NAME);
private static final File SERVER_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.SERVER_KEYSTORE);
private static final File SERVER_TRUSTSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.SERVER_TRUSTSTORE);
private static final File CLIENT_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.CLIENT_KEYSTORE);
private static final File CLIENT_TRUSTSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.CLIENT_TRUSTSTORE);
private static final File UNTRUSTED_STORE_FILE = new File(WORK_DIR, SecurityTestConstants.UNTRUSTED_KEYSTORE);
private static final String PASSWORD = SecurityTestConstants.KEYSTORE_PASSWORD;
private static URL securedRootUrl;
// just to make server setup task work
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, NAME + ".war")
.add(new StringAsset("index page"), "index.html");
}
@BeforeClass
public static void setSecuredRootUrl() throws Exception {
try {
securedRootUrl = new URL("https", TestSuiteEnvironment.getServerAddress(), HTTPS_PORT, "");
} catch (MalformedURLException ex) {
throw new IllegalStateException("Unable to create HTTPS URL to server root", ex);
}
}
@Test
public void testSendingTrustedClientCertificate() {
HttpClient client = SSLTruststoreUtil
.getHttpClientWithSSL(CLIENT_KEYSTORE_FILE, PASSWORD, CLIENT_TRUSTSTORE_FILE, PASSWORD);
assertConnectionToServer(client, SC_OK);
closeClient(client);
}
@Test
public void testSendingNonTrustedClientCertificateFails() {
HttpClient client = SSLTruststoreUtil
.getHttpClientWithSSL(UNTRUSTED_STORE_FILE, PASSWORD, CLIENT_TRUSTSTORE_FILE, PASSWORD);
assertSslHandshakeFails(client);
closeClient(client);
}
@Test
public void testSendingNoClientCertificateFails() {
HttpClient client = SSLTruststoreUtil.getHttpClientWithSSL(CLIENT_TRUSTSTORE_FILE, PASSWORD);
assertSslHandshakeFails(client);
closeClient(client);
}
/**
* RESTEasy client loads truststore from Elytron client configuration. This truststore contains correct server certificate.
*/
@Test
public void testResteasyElytronClientTrustedServer() {
AuthenticationContext context = doPrivileged((PrivilegedAction<AuthenticationContext>) () -> {
try {
URL config = getClass().getResource("wildfly-config-correct-truststore.xml");
return ElytronXmlParser.parseAuthenticationClientConfiguration(config.toURI()).create();
} catch (Throwable t) {
throw new InvalidAuthenticationConfigurationException(t);
}
});
context.run(() -> {
ClientBuilder resteasyClientBuilder = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true);
Client client = resteasyClientBuilder.build();
Response response = client.target(String.valueOf(securedRootUrl)).request().get();
Assert.assertEquals(200, response.getStatus());
});
}
/**
* RESTEasy client loads SSL Context from Elytron client config.
* This SSL Context does not have truststore configured, so exception is expected.
*/
@Test(expected = ProcessingException.class)
public void testResteasyElytronClientMissingTruststore() {
AuthenticationContext context = doPrivileged((PrivilegedAction<AuthenticationContext>) () -> {
try {
URL config = getClass().getResource("wildfly-config-correct-truststore-missing.xml");
return ElytronXmlParser.parseAuthenticationClientConfiguration(config.toURI()).create();
} catch (Throwable t) {
throw new InvalidAuthenticationConfigurationException(t);
}
});
context.run(() -> {
ClientBuilder resteasyClientBuilder = ClientBuilder.newBuilder();
Client client = resteasyClientBuilder.build();
Response response = client.target(String.valueOf(securedRootUrl)).request().get();
Assert.assertEquals("Hello World!", response.readEntity(String.class));
Assert.assertEquals(200, response.getStatus());
});
}
/**
* Elytron client has configured truststore that does not contain server's certificate.
* Test will pass because Elytron config is ignored since different ssl context is specified on RESTEasy client builder specifically.
*/
@Test
public void testClientConfigProviderSSLContextIgnoredIfDifferentIsSet() throws URISyntaxException, GeneralSecurityException {
AuthenticationContextConfigurationClient AUTH_CONTEXT_CLIENT =
AccessController.doPrivileged((PrivilegedAction<AuthenticationContextConfigurationClient>) AuthenticationContextConfigurationClient::new);
AuthenticationContext context = doPrivileged((PrivilegedAction<AuthenticationContext>) () -> {
try {
URL config = getClass().getResource("wildfly-config-correct-truststore-missing.xml");
return ElytronXmlParser.parseAuthenticationClientConfiguration(config.toURI()).create();
} catch (Throwable t) {
throw new InvalidAuthenticationConfigurationException(t);
}
});
AuthenticationContext contextWithTruststore = doPrivileged((PrivilegedAction<AuthenticationContext>) () -> {
try {
URL config = getClass().getResource("wildfly-config-correct-truststore.xml");
return ElytronXmlParser.parseAuthenticationClientConfiguration(config.toURI()).create();
} catch (Throwable t) {
throw new InvalidAuthenticationConfigurationException(t);
}
});
SSLContext sslContext = AUTH_CONTEXT_CLIENT.getSSLContext(securedRootUrl.toURI(), contextWithTruststore);
context.run(() -> {
ClientBuilder resteasyClientBuilder = ClientBuilder.newBuilder();
resteasyClientBuilder.sslContext(sslContext).hostnameVerifier((s, sslSession) -> true);
Client client = resteasyClientBuilder.build();
Response response = client.target(String.valueOf(securedRootUrl)).request().get();
Assert.assertEquals(200, response.getStatus());
});
}
/**
* Test situation when credentials are set on RESTEeasy client, but truststore is part of SSLContext configured for Elytron client.
* Test that Elytron SSLContext will be used successfully.
*/
@Test
public void testClientConfigProviderSSLContextIsSuccessfulWhenBasicSetOnRESTEasy() {
AuthenticationContext context = doPrivileged((PrivilegedAction<AuthenticationContext>) () -> {
try {
URL config = getClass().getResource("wildfly-config-correct-truststore.xml");
return ElytronXmlParser.parseAuthenticationClientConfiguration(config.toURI()).create();
} catch (Throwable t) {
throw new InvalidAuthenticationConfigurationException(t);
}
});
context.run(() -> {
ClientBuilder resteasyClientBuilder = ClientBuilder.newBuilder();
resteasyClientBuilder.hostnameVerifier((s, sslSession) -> true);
Client client = resteasyClientBuilder.build();
client.register(HttpAuthorization.basic("randomName", "randomPass"));
Response response = client.target(String.valueOf(securedRootUrl)).request().get();
Assert.assertEquals(200, response.getStatus());
});
}
/**
* Test that RESTEasy client does choose SSLContext from Elytron client based on destination of the request.
* In this case the truststore is set for different endpoint/server and so SSL handshake will fail.
*/
@Test(expected = ProcessingException.class)
public void testClientConfigProviderSSLContextForDifferentHostWillNotWork() {
AuthenticationContext context = doPrivileged((PrivilegedAction<AuthenticationContext>) () -> {
try {
URL config = getClass().getResource("wildfly-config-correct-truststore-different-host.xml");
return ElytronXmlParser.parseAuthenticationClientConfiguration(config.toURI()).create();
} catch (Throwable t) {
throw new InvalidAuthenticationConfigurationException(t);
}
});
context.run(() -> {
ClientBuilder resteasyClientBuilder = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true);
Client client = resteasyClientBuilder.build();
Response response = client.target(String.valueOf(securedRootUrl)).request().get();
Assert.assertEquals(200, response.getStatus());
});
}
/**
* Test that RESTEasy client does choose SSLContext from Elytron client based on destination of the request.
* In this case the truststore is set for correct endpoint/server and so SSL handshake will succeed.
*/
@Test
public void testClientConfigProviderSSLContextForCorrectHostWillWork() {
AuthenticationContext context = doPrivileged((PrivilegedAction<AuthenticationContext>) () -> {
try {
URL config = getClass().getResource("wildfly-config-correct-truststore-correct-host.xml");
return ElytronXmlParser.parseAuthenticationClientConfiguration(config.toURI()).create();
} catch (Throwable t) {
throw new InvalidAuthenticationConfigurationException(t);
}
});
context.run(() -> {
ClientBuilder resteasyClientBuilder = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true);
Client client = resteasyClientBuilder.build();
Response response = client.target(String.valueOf(securedRootUrl)).request().get();
Assert.assertEquals(200, response.getStatus());
});
}
private void assertConnectionToServer(HttpClient client, int expectedStatusCode) {
try {
Utils.makeCallWithHttpClient(securedRootUrl, client, expectedStatusCode);
} catch (IOException | URISyntaxException ex) {
throw new IllegalStateException("Unable to request server root over HTTPS", ex);
}
}
private void assertSslHandshakeFails(HttpClient client) {
try {
Utils.makeCallWithHttpClient(securedRootUrl, client, SC_OK);
} catch (SSLHandshakeException | SocketException e) {
// expected
return;
} catch (SSLException e) {
if (e.getCause() instanceof SocketException) return; // expected
throw new IllegalStateException("Unexpected SSLException", e);
} catch (IOException | URISyntaxException ex) {
throw new IllegalStateException("Unable to request server root over HTTPS", ex);
}
fail("SSL handshake should fail");
}
private void closeClient(HttpClient client) {
try {
((CloseableHttpClient) client).close();
} catch (IOException ex) {
throw new IllegalStateException("Unable to close HTTP client", ex);
}
}
/**
* Creates Elytron server-ssl-context and key/trust stores.
*/
static class ElytronSslContextInUndertowSetupTask extends AbstractElytronSetupTask {
@Override
protected void setup(final ModelControllerClient modelControllerClient) throws Exception {
keyMaterialSetup(WORK_DIR);
super.setup(modelControllerClient);
}
@Override
protected ConfigurableElement[] getConfigurableElements() {
return new ConfigurableElement[] {
SimpleKeyStore.builder().withName(NAME + SecurityTestConstants.SERVER_KEYSTORE)
.withPath(Path.builder().withPath(SERVER_KEYSTORE_FILE.getPath()).build())
.withCredentialReference(CredentialReference.builder().withClearText(PASSWORD).build())
.build(),
SimpleKeyStore.builder().withName(NAME + SecurityTestConstants.SERVER_TRUSTSTORE)
.withPath(Path.builder().withPath(SERVER_TRUSTSTORE_FILE.getPath()).build())
.withCredentialReference(CredentialReference.builder().withClearText(PASSWORD).build())
.build(),
SimpleKeyManager.builder().withName(NAME)
.withKeyStore(NAME + SecurityTestConstants.SERVER_KEYSTORE)
.withCredentialReference(CredentialReference.builder().withClearText(PASSWORD).build())
.build(),
SimpleTrustManager.builder().withName(NAME)
.withKeyStore(NAME + SecurityTestConstants.SERVER_TRUSTSTORE)
.build(),
SimpleServerSslContext.builder().withName(NAME)
.withKeyManagers(NAME)
.withTrustManagers(NAME)
.withNeedClientAuth(true)
.build(),
UndertowSslContext.builder().withName(NAME).build()
};
}
@Override
protected void tearDown(ModelControllerClient modelControllerClient) throws Exception {
super.tearDown(modelControllerClient);
FileUtils.deleteDirectory(WORK_DIR);
}
protected static void keyMaterialSetup(File workDir) throws Exception {
FileUtils.deleteDirectory(workDir);
workDir.mkdirs();
Assert.assertTrue(workDir.exists());
Assert.assertTrue(workDir.isDirectory());
CoreUtils.createKeyMaterial(workDir);
}
}
}
| 18,596
| 48.198413
| 154
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ssl/AutomaticSelfSignedCertificateGenerationTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, 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.ssl;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
import static org.jboss.as.test.integration.security.common.SSLTruststoreUtil.HTTPS_PORT;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.CloseableHttpClient;
import org.codehaus.plexus.util.FileUtils;
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.controller.client.ModelControllerClient;
import org.jboss.as.test.categories.CommonCriteria;
import org.jboss.as.test.integration.management.util.CLIWrapper;
import org.jboss.as.test.integration.security.common.SSLTruststoreUtil;
import org.jboss.as.test.integration.security.common.SecurityTestConstants;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.SimpleServlet;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.test.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
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.elytron.UndertowSslContext;
/**
* Tests for the automatic creation of a lazily generated self-signed certificate when Elytron
* is in use.
*
* @author <a href="mailto:fjuma@redhat.com">Farah Juma</a>
*/
@RunWith(Arquillian.class)
@ServerSetup({ AutomaticSelfSignedCertificateGenerationTestCase.ElytronAndUndertowSetupTask.class })
@RunAsClient
@Category(CommonCriteria.class)
public class AutomaticSelfSignedCertificateGenerationTestCase {
private static final String NAME = AutomaticSelfSignedCertificateGenerationTestCase.class.getSimpleName();
private static final File WORK_DIR = new File("target" + File.separatorChar + NAME);
private static final File SERVER_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.SERVER_KEYSTORE);
private static final File CLIENT_TRUSTSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.CLIENT_TRUSTSTORE);
private static final String PASSWORD = SecurityTestConstants.KEYSTORE_PASSWORD;
private static final String GENERATE_SELF_SIGNED_CERTIFICATE_HOST="customHostName";
private static final String SERVER_ALIAS = "server";
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, NAME + ".war").addClasses(SimpleServlet.class);
}
@Test
public void testSelfSignedCertificateGenerated() throws Exception {
final URL servletUrl = new URL("https", TestSuiteEnvironment.getServerAddress(), HTTPS_PORT,
"/" + NAME + "/" + SimpleServlet.SERVLET_PATH.substring(1));
HttpClient client = SSLTruststoreUtil.getHttpClientWithSSL(null, null);
try {
assertFalse(SERVER_KEYSTORE_FILE.exists()); // keystore doesn't exist initially
try {
// attempt to access the https interface
Utils.makeCallWithHttpClient(servletUrl, client, SC_OK);
} catch (SSLHandshakeException expected) {
}
// keystore should now exist and should contain a self-signed certificate
assertTrue(SERVER_KEYSTORE_FILE.exists());
X509Certificate serverCert;
try (FileInputStream is = new FileInputStream(SERVER_KEYSTORE_FILE.getAbsolutePath())) {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(is, PASSWORD.toCharArray());
assertEquals(1, keyStore.size());
serverCert = (X509Certificate) keyStore.getCertificate(SERVER_ALIAS);
assertEquals(serverCert.getSubjectX500Principal(), serverCert.getIssuerX500Principal());
assertEquals("CN=" + GENERATE_SELF_SIGNED_CERTIFICATE_HOST, serverCert.getSubjectX500Principal().getName());
}
// add the server's newly generated certificate to the client's truststore
try (FileOutputStream fos = new FileOutputStream(CLIENT_TRUSTSTORE_FILE)) {
KeyStore trustStore = KeyStore.getInstance("PKCS12");
trustStore.load(null, null);
trustStore.setCertificateEntry("server", serverCert);
trustStore.store(fos, PASSWORD.toCharArray());
}
try {
// attempt to access the https interface again
client = SSLTruststoreUtil.getHttpClientWithSSL(CLIENT_TRUSTSTORE_FILE, PASSWORD, "PKCS12");
Utils.makeCallWithHttpClient(servletUrl, client, SC_OK);
} catch (IOException | URISyntaxException ex) {
throw new IllegalStateException("Unable to request server root over HTTPS", ex);
} finally {
if (CLIENT_TRUSTSTORE_FILE.exists()) {
CLIENT_TRUSTSTORE_FILE.delete();
}
}
try (FileInputStream is = new FileInputStream(SERVER_KEYSTORE_FILE.getAbsolutePath())) {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(is, PASSWORD.toCharArray());
assertEquals(1, keyStore.size());
assertEquals(serverCert, keyStore.getCertificate(SERVER_ALIAS)); // server's certificate should be unchanged
}
} finally {
closeClient(client);
}
}
@Test
public void testSelfSignedCertificateNotGeneratedIfGenerateAttributeUndefined() throws Exception {
// undefine generate-self-signed-certificate-host
try (CLIWrapper cli = new CLIWrapper(true)) {
cli.sendLine(String.format("/subsystem=elytron/key-manager=%s:undefine-attribute(name=generate-self-signed-certificate-host)",
NAME));
cli.sendLine(String.format("reload"));
}
try {
final URL servletUrl = new URL("https", TestSuiteEnvironment.getServerAddress(), HTTPS_PORT,
"/" + NAME + "/" + SimpleServlet.SERVLET_PATH.substring(1));
HttpClient client = SSLTruststoreUtil.getHttpClientWithSSL(null, null);
assertFalse(SERVER_KEYSTORE_FILE.exists()); // keystore doesn't exist
try {
// attempt to access the https interface
Utils.makeCallWithHttpClient(servletUrl, client, SC_OK);
fail("Expected SSLHandshakeException not thrown");
} catch (SSLHandshakeException expected) {
}
assertFalse(SERVER_KEYSTORE_FILE.exists()); // keystore wasn't created
} finally {
// clean up
try (CLIWrapper cli = new CLIWrapper(true)) {
cli.sendLine(String.format("/subsystem=elytron/key-manager=%s:write-attribute(name=generate-self-signed-certificate-host,value=%s)",
NAME, GENERATE_SELF_SIGNED_CERTIFICATE_HOST));
cli.sendLine(String.format("reload"));
}
}
}
static class ElytronAndUndertowSetupTask extends AbstractElytronSetupTask {
@Override
protected void setup(final ModelControllerClient modelControllerClient) throws Exception {
if (WORK_DIR.exists()) {
FileUtils.deleteDirectory(WORK_DIR);
}
WORK_DIR.mkdirs();
super.setup(modelControllerClient);
}
@Override
protected ConfigurableElement[] getConfigurableElements() {
return new ConfigurableElement[] {
SimpleKeyStore.builder().withName(NAME + SecurityTestConstants.SERVER_KEYSTORE)
.withPath(Path.builder().withPath(SERVER_KEYSTORE_FILE.getAbsolutePath()).build())
.withCredentialReference(CredentialReference.builder().withClearText(PASSWORD).build())
.withType("PKCS12")
.build(),
SimpleKeyManager.builder().withName(NAME)
.withKeyStore(NAME + SecurityTestConstants.SERVER_KEYSTORE)
.withCredentialReference(CredentialReference.builder().withClearText(PASSWORD).build())
.withGenerateSelfSignedCertificateHost(GENERATE_SELF_SIGNED_CERTIFICATE_HOST)
.build(),
SimpleServerSslContext.builder().withName(NAME)
.withKeyManagers(NAME)
.build(),
UndertowSslContext.builder().withName(NAME).build()
};
}
@Override
protected void tearDown(ModelControllerClient modelControllerClient) throws Exception {
super.tearDown(modelControllerClient);
FileUtils.deleteDirectory(WORK_DIR);
}
}
private void closeClient(HttpClient client) {
try {
((CloseableHttpClient) client).close();
} catch (IOException ex) {
throw new IllegalStateException("Unable to close HTTP client", ex);
}
}
}
| 11,195
| 48.105263
| 148
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realmmappers/MappedRegexRealmMapperTestCase.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.wildfly.test.integration.elytron.realmmappers;
import java.net.URL;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
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.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.Utils;
import org.jboss.as.test.shared.ServerReload;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.wildfly.test.integration.elytron.realmmappers.AbstractRealmMapperTest.DEPLOYMENT;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.CORRECT_PASSWORD;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.REALM1;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.REALM2;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.REALM3;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.USER_IN_DEFAULT_REALM;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.USER_IN_DEFAULT_REALM_MAPPED;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.USER_IN_REALM1;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.USER_IN_REALM1_WITH_INFIX_AND_SUFFIX;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.USER_IN_REALM1_WITH_REALM;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.USER_IN_REALM1_WITH_REALM_AND_DIFFERENT_SUFFIX;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.USER_IN_REALM1_WITH_REALM_AND_SUFFIX;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.USER_IN_REALM2;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.USER_IN_REALM2_WITH_REALM1;
/**
* Test case for 'mapped-regex-realm-mapper' Elytron subsystem resource.
*
* @author olukas
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({RealmMapperServerSetupTask.class, MappedRegexRealmMapperTestCase.SetupTask.class})
public class MappedRegexRealmMapperTestCase extends AbstractRealmMapperTest {
private static final String COMMON_REALM_MAPPER = "commonRealmMapper";
private static final String MAP_EXISTED_REALM_MAPPER = "mapExistedRealmMapper";
private static final String MAP_NONEXISTED_REALM_MAPPER = "mapNonExistedRealmMapper";
private static final String TWO_CAPTURE_GROUPS_REALM_MAPPER = "twoCaptureGroupsRealmMapper";
private static final String DELEGATE_REALM_MAPPER = "delegateRealmMapper";
private static final String DELEGATE_REALM_MAPPER_WITH_MAPPING = "delegateRealmMapperWithMapping";
private static final String DELEGATED_REALM_MAPPER = "delagetedConstantRealmMapper";
/**
* Test whether mapped realm is chosen when user matches pattern and obtained realm is mapped in realm-map.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testUserMatchMappingExists(@ArquillianResource URL webAppURL) throws Exception {
setupRealmMapper(COMMON_REALM_MAPPER);
try {
assertEquals("Response body is not correct.", USER_IN_REALM1_WITH_REALM_AND_SUFFIX,
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_REALM1_WITH_REALM_AND_SUFFIX, CORRECT_PASSWORD, SC_OK));
} finally {
undefineRealmMapper();
}
}
/**
* Test whether default realm is chosen when user matches pattern and obtained realm is not mapped in realm-map.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testUserMatchMappingNotExist(@ArquillianResource URL webAppURL) throws Exception {
setupRealmMapper(COMMON_REALM_MAPPER);
try {
assertEquals("Response body is not correct.", USER_IN_DEFAULT_REALM_MAPPED,
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_DEFAULT_REALM_MAPPED, CORRECT_PASSWORD, SC_OK));
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_REALM1_WITH_REALM_AND_DIFFERENT_SUFFIX, CORRECT_PASSWORD, SC_UNAUTHORIZED);
} finally {
undefineRealmMapper();
}
}
/**
* Test whether mapped realm is chosen when user matches pattern and obtained realm exists but is also mapped in realm-map.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testUserMatchAndMapExistedRealm(@ArquillianResource URL webAppURL) throws Exception {
setupRealmMapper(MAP_EXISTED_REALM_MAPPER);
try {
assertEquals("Response body is not correct.", USER_IN_REALM2_WITH_REALM1,
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_REALM2_WITH_REALM1, CORRECT_PASSWORD, SC_OK));
} finally {
undefineRealmMapper();
}
}
/**
* Test whether default realm is used when mapped realm does not exist.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testUserMatchAndMappedRealmDoesNotExist(@ArquillianResource URL webAppURL) throws Exception {
setupRealmMapper(MAP_NONEXISTED_REALM_MAPPER);
try {
assertEquals("Response body is not correct.", USER_IN_DEFAULT_REALM_MAPPED,
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_DEFAULT_REALM_MAPPED, CORRECT_PASSWORD, SC_OK));
} finally {
undefineRealmMapper();
}
}
/**
* Test whether default realm is chosen when user does not match pattern.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testUserDoNotMatch(@ArquillianResource URL webAppURL) throws Exception {
setupRealmMapper(COMMON_REALM_MAPPER);
try {
assertEquals("Response body is not correct.", USER_IN_DEFAULT_REALM,
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_DEFAULT_REALM, CORRECT_PASSWORD, SC_OK));
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_REALM1, CORRECT_PASSWORD, SC_UNAUTHORIZED);
} finally {
undefineRealmMapper();
}
}
/**
* Test whether delegate-realm-mapper is not used when user matches pattern.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testDoNotDelegateWhenMatch(@ArquillianResource URL webAppURL) throws Exception {
setupRealmMapper(DELEGATE_REALM_MAPPER);
try {
assertEquals("Response body is not correct.", USER_IN_REALM1_WITH_REALM_AND_SUFFIX,
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_REALM1_WITH_REALM_AND_SUFFIX, CORRECT_PASSWORD, SC_OK));
} finally {
undefineRealmMapper();
}
}
/**
* Test whether delegate-realm-mapper is used when user does not match pattern.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testDelegateWhenDoNotMatch(@ArquillianResource URL webAppURL) throws Exception {
setupRealmMapper(DELEGATE_REALM_MAPPER);
try {
assertEquals("Response body is not correct.", USER_IN_REALM2,
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_REALM2, CORRECT_PASSWORD, SC_OK));
} finally {
undefineRealmMapper();
}
}
/**
* Test whether mapped realm is chosen even if delegate-realm-mapper is set when user matches pattern and obtained realm
* exists but is also mapped in realm-map.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testUserMatchAndMapExistedRealmWithDelegateSet(@ArquillianResource URL webAppURL) throws Exception {
setupRealmMapper(DELEGATE_REALM_MAPPER_WITH_MAPPING);
try {
assertEquals("Response body is not correct.", USER_IN_REALM2_WITH_REALM1,
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_REALM2_WITH_REALM1, CORRECT_PASSWORD, SC_OK));
} finally {
undefineRealmMapper();
}
}
/**
* Test whether default realm is chosen even if delegate-realm-mapper is set when user matches pattern and obtained realm is
* not mapped in realm-map and obtained realm does not exist.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testUserMatchMappingNotExistAndInvalidRealmWithDelegateSet(@ArquillianResource URL webAppURL) throws Exception {
setupRealmMapper(DELEGATE_REALM_MAPPER_WITH_MAPPING);
try {
assertEquals("Response body is not correct.", USER_IN_DEFAULT_REALM_MAPPED,
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_DEFAULT_REALM_MAPPED, CORRECT_PASSWORD, SC_OK));
} finally {
undefineRealmMapper();
}
}
/**
* Test whether realm is parsed from first capture group if more capture groups are used.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testMoreCaptureGroups(@ArquillianResource URL webAppURL) throws Exception {
setupRealmMapper(TWO_CAPTURE_GROUPS_REALM_MAPPER);
try {
assertEquals("Response body is not correct.", USER_IN_REALM1_WITH_INFIX_AND_SUFFIX,
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_REALM1_WITH_INFIX_AND_SUFFIX, CORRECT_PASSWORD, SC_OK));
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_REALM1_WITH_REALM, CORRECT_PASSWORD, SC_UNAUTHORIZED);
} finally {
undefineRealmMapper();
}
}
static class SetupTask implements ServerSetupTask {
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
cli.sendLine(String.format("/subsystem=elytron/constant-realm-mapper=%s:add(realm-name=%s)",
DELEGATED_REALM_MAPPER, REALM3));
cli.sendLine(String.format("/subsystem=elytron/mapped-regex-realm-mapper=%s:add(pattern=\".*&(.*)\",realm-map={suffix=%s}",
COMMON_REALM_MAPPER, REALM1));
cli.sendLine(String.format("/subsystem=elytron/mapped-regex-realm-mapper=%s:add(pattern=\".*&(.*)\",realm-map={%s=%s}",
MAP_EXISTED_REALM_MAPPER, REALM1, REALM2));
cli.sendLine(String.format("/subsystem=elytron/mapped-regex-realm-mapper=%s:add(pattern=\".*&(.*)\",realm-map={mapped=nonExist}",
MAP_NONEXISTED_REALM_MAPPER));
cli.sendLine(String.format("/subsystem=elytron/mapped-regex-realm-mapper=%s:add(pattern=\".*@(.*)&(.*)\",realm-map={infix=%s})",
TWO_CAPTURE_GROUPS_REALM_MAPPER, REALM1));
cli.sendLine(String.format("/subsystem=elytron/mapped-regex-realm-mapper=%s:add(delegate-realm-mapper=%s,pattern=\".*&(.*)\",realm-map={suffix=%s,%s=%s}",
DELEGATE_REALM_MAPPER, DELEGATED_REALM_MAPPER, REALM1, REALM3, REALM2));
cli.sendLine(String.format("/subsystem=elytron/mapped-regex-realm-mapper=%s:add(delegate-realm-mapper=%s,pattern=\".*&(.*)\",realm-map={%s=%s}",
DELEGATE_REALM_MAPPER_WITH_MAPPING, DELEGATED_REALM_MAPPER, REALM1, REALM2));
}
ServerReload.reloadIfRequired(managementClient);
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
cli.sendLine(String.format("/subsystem=elytron/mapped-regex-realm-mapper=%s:remove()",
DELEGATE_REALM_MAPPER_WITH_MAPPING));
cli.sendLine(String.format("/subsystem=elytron/mapped-regex-realm-mapper=%s:remove()", DELEGATE_REALM_MAPPER));
cli.sendLine(String.format("/subsystem=elytron/mapped-regex-realm-mapper=%s:remove()",
TWO_CAPTURE_GROUPS_REALM_MAPPER));
cli.sendLine(String.format("/subsystem=elytron/mapped-regex-realm-mapper=%s:remove()", MAP_NONEXISTED_REALM_MAPPER));
cli.sendLine(String.format("/subsystem=elytron/mapped-regex-realm-mapper=%s:remove()", MAP_EXISTED_REALM_MAPPER));
cli.sendLine(String.format("/subsystem=elytron/mapped-regex-realm-mapper=%s:remove()", COMMON_REALM_MAPPER));
cli.sendLine(String.format("/subsystem=elytron/constant-realm-mapper=%s:remove()", DELEGATED_REALM_MAPPER));
}
ServerReload.reloadIfRequired(managementClient);
}
}
}
| 14,892
| 48.478405
| 170
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realmmappers/SimpleRegexRealmMapperTestCase.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.wildfly.test.integration.elytron.realmmappers;
import java.net.URL;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
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.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.Utils;
import org.jboss.as.test.shared.ServerReload;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.wildfly.test.integration.elytron.realmmappers.AbstractRealmMapperTest.DEPLOYMENT;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.CORRECT_PASSWORD;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.REALM3;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.USER_IN_DEFAULT_REALM;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.USER_IN_DEFAULT_REALM_MAPPED2;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.USER_IN_REALM1;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.USER_IN_REALM1_WITH_REALM;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.USER_IN_REALM1_WITH_REALM_AND_SUFFIX;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.USER_IN_REALM3;
/**
* Test case for 'simple-regex-realm-mapper' Elytron subsystem resource.
*
* @author olukas
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({RealmMapperServerSetupTask.class, SimpleRegexRealmMapperTestCase.SetupTask.class})
public class SimpleRegexRealmMapperTestCase extends AbstractRealmMapperTest {
private static final String COMMON_REALM_MAPPER = "commonRealmMapper";
private static final String TWO_CAPTURE_GROUPS_REALM_MAPPER = "twoCaptureGroupsRealmMapper";
private static final String DELEGATE_REALM_MAPPER = "delegateRealmMapper";
private static final String DELEGATED_REALM_MAPPER = "delagetedConstantRealmMapper";
/**
* Test whether obtained realm is used when user matches pattern and obtained realm exists.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testUserMatch(@ArquillianResource URL webAppURL) throws Exception {
setupRealmMapper(COMMON_REALM_MAPPER);
try {
assertEquals("Response body is not correct.", USER_IN_REALM1_WITH_REALM,
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_REALM1_WITH_REALM, CORRECT_PASSWORD, SC_OK));
} finally {
undefineRealmMapper();
}
}
/**
* Test whether default realm is used when user matches pattern and obtained realm does not exist.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testUserMatchRealmDoesNotExist(@ArquillianResource URL webAppURL) throws Exception {
setupRealmMapper(COMMON_REALM_MAPPER);
try {
assertEquals("Response body is not correct.", USER_IN_DEFAULT_REALM_MAPPED2,
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_DEFAULT_REALM_MAPPED2, CORRECT_PASSWORD, SC_OK));
} finally {
undefineRealmMapper();
}
}
/**
* Test whether default realm is used when user does not match pattern.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testUserDoNotMatch(@ArquillianResource URL webAppURL) throws Exception {
setupRealmMapper(COMMON_REALM_MAPPER);
try {
assertEquals("Response body is not correct.", USER_IN_DEFAULT_REALM,
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_DEFAULT_REALM, CORRECT_PASSWORD, SC_OK));
} finally {
undefineRealmMapper();
}
}
/**
* Test whether obtained realm is used even if delegate-realm-mapper is set when user matches pattern and obtained realm
* exists.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testDoNotDelegateWhenMatch(@ArquillianResource URL webAppURL) throws Exception {
setupRealmMapper(DELEGATE_REALM_MAPPER);
try {
assertEquals("Response body is not correct.", USER_IN_REALM1_WITH_REALM,
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_REALM1_WITH_REALM, CORRECT_PASSWORD, SC_OK));
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_REALM1, CORRECT_PASSWORD, SC_UNAUTHORIZED);
} finally {
undefineRealmMapper();
}
}
/**
* Test whether mapper from delegate-realm-mapper is used when user does not match pattern.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testDelegateWhenDoNotMatch(@ArquillianResource URL webAppURL) throws Exception {
setupRealmMapper(DELEGATE_REALM_MAPPER);
try {
assertEquals("Response body is not correct.", USER_IN_REALM3,
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_REALM3, CORRECT_PASSWORD, SC_OK));
} finally {
undefineRealmMapper();
}
}
/**
* Test whether realm is parsed from first capture group if more capture groups are used.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testMoreCaptureGroups(@ArquillianResource URL webAppURL) throws Exception {
setupRealmMapper(TWO_CAPTURE_GROUPS_REALM_MAPPER);
try {
assertEquals("Response body is not correct.", USER_IN_REALM1_WITH_REALM_AND_SUFFIX,
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_REALM1_WITH_REALM_AND_SUFFIX, CORRECT_PASSWORD, SC_OK));
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_REALM1_WITH_REALM, CORRECT_PASSWORD, SC_UNAUTHORIZED);
} finally {
undefineRealmMapper();
}
}
static class SetupTask implements ServerSetupTask {
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
cli.sendLine(String.format("/subsystem=elytron/constant-realm-mapper=%s:add(realm-name=%s)",
DELEGATED_REALM_MAPPER, REALM3));
cli.sendLine(String.format("/subsystem=elytron/simple-regex-realm-mapper=%s:add(pattern=\".*@(.*)\")",
COMMON_REALM_MAPPER));
cli.sendLine(String.format("/subsystem=elytron/simple-regex-realm-mapper=%s:add(pattern=\".*@(.*)&(.*)\")",
TWO_CAPTURE_GROUPS_REALM_MAPPER));
cli.sendLine(String.format("/subsystem=elytron/simple-regex-realm-mapper=%s:add(delegate-realm-mapper=%s,pattern=\".*@(.*)\")",
DELEGATE_REALM_MAPPER, DELEGATED_REALM_MAPPER));
}
ServerReload.reloadIfRequired(managementClient);
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
cli.sendLine(String.format("/subsystem=elytron/simple-regex-realm-mapper=%s:remove()", DELEGATE_REALM_MAPPER));
cli.sendLine(String.format("/subsystem=elytron/simple-regex-realm-mapper=%s:remove()",
TWO_CAPTURE_GROUPS_REALM_MAPPER));
cli.sendLine(String.format("/subsystem=elytron/simple-regex-realm-mapper=%s:remove()", COMMON_REALM_MAPPER));
cli.sendLine(String.format("/subsystem=elytron/constant-realm-mapper=%s:remove()", DELEGATED_REALM_MAPPER));
}
ServerReload.reloadIfRequired(managementClient);
}
}
}
| 9,691
| 45.596154
| 143
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realmmappers/AbstractRealmMapperTest.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.wildfly.test.integration.elytron.realmmappers;
import java.net.MalformedURLException;
import java.net.URL;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.as.test.integration.management.util.CLIWrapper;
import org.jboss.as.test.integration.security.common.SecurityTestConstants;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.SECURITY_DOMAIN_REFERENCE;
import org.wildfly.test.security.servlets.SecuredPrincipalPrintingServlet;
/**
*
* @author olukas
*/
public abstract class AbstractRealmMapperTest {
protected static final String DEPLOYMENT = "dep";
@Deployment(name = DEPLOYMENT)
public static WebArchive createWar() {
return ShrinkWrap.create(WebArchive.class, DEPLOYMENT + ".war").addClasses(SecuredPrincipalPrintingServlet.class)
.addAsWebInfResource(Utils.getJBossWebXmlAsset(SECURITY_DOMAIN_REFERENCE), "jboss-web.xml")
.addAsWebInfResource(new StringAsset(SecurityTestConstants.WEB_XML_BASIC_AUTHN), "web.xml");
}
protected void setupRealmMapper(String realmMapperName) throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
cli.sendLine(String.format("/subsystem=elytron/security-domain=%s:write-attribute(name=realm-mapper,value=%s)",
RealmMapperServerSetupTask.SECURITY_DOMAIN_NAME, realmMapperName));
cli.sendLine(String.format("reload"));
}
}
protected void undefineRealmMapper() throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
cli.sendLine(String.format("/subsystem=elytron/security-domain=%s:undefine-attribute(name=realm-mapper)",
RealmMapperServerSetupTask.SECURITY_DOMAIN_NAME));
cli.sendLine(String.format("reload"));
}
}
protected URL principalServlet(URL url) throws MalformedURLException {
return new URL(url.toExternalForm() + SecuredPrincipalPrintingServlet.SERVLET_PATH.substring(1));
}
}
| 3,280
| 45.211268
| 123
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realmmappers/ConstantRealmMapperTestCase.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.wildfly.test.integration.elytron.realmmappers;
import java.net.URL;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
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.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.Utils;
import org.jboss.as.test.shared.ServerReload;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.CORRECT_PASSWORD;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.DEFAULT_REALM;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.REALM1;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.REALM2;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.USER_IN_DEFAULT_REALM;
import static org.wildfly.test.integration.elytron.realmmappers.RealmMapperServerSetupTask.USER_IN_REALM1;
/**
* Test case for 'constant-realm-mapper' Elytron subsystem resource.
*
* @author olukas
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({RealmMapperServerSetupTask.class, ConstantRealmMapperTestCase.SetupTask.class})
public class ConstantRealmMapperTestCase extends AbstractRealmMapperTest {
private static final String DEFAULT_REALM_MAPPER = "defaultRealmMapper";
private static final String REALM1_MAPPER = "realm1Mapper";
private static final String REALM2_MAPPER = "realm2Mapper";
private static final String NON_EXIST_MAPPER = "nonExistMapper";
/**
* Test whether default realm is used in security domain when no realm-mapper is configured.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testDefaultRealmWithoutAnyRealmMapper(@ArquillianResource URL webAppURL) throws Exception {
assertEquals("Response body is not correct.", USER_IN_DEFAULT_REALM,
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_DEFAULT_REALM, CORRECT_PASSWORD, SC_OK));
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_REALM1, CORRECT_PASSWORD, SC_UNAUTHORIZED);
}
/**
* Test whether constant realm mapper return expected value. It means that security domain uses expected realm instead of
* default.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testRealmMapper(@ArquillianResource URL webAppURL) throws Exception {
setupRealmMapper(REALM1_MAPPER);
try {
assertEquals("Response body is not correct.", USER_IN_REALM1,
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_REALM1, CORRECT_PASSWORD, SC_OK));
Utils.makeCallWithBasicAuthn(principalServlet(webAppURL), USER_IN_DEFAULT_REALM, CORRECT_PASSWORD, SC_UNAUTHORIZED);
} finally {
undefineRealmMapper();
}
}
static class SetupTask implements ServerSetupTask {
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
cli.sendLine(String.format("/subsystem=elytron/constant-realm-mapper=%s:add(realm-name=%s)",
DEFAULT_REALM_MAPPER, DEFAULT_REALM));
cli.sendLine(String.format("/subsystem=elytron/constant-realm-mapper=%s:add(realm-name=%s)",
REALM1_MAPPER, REALM1));
cli.sendLine(String.format("/subsystem=elytron/constant-realm-mapper=%s:add(realm-name=%s)",
REALM2_MAPPER, REALM2));
cli.sendLine(String.format("/subsystem=elytron/constant-realm-mapper=%s:add(realm-name=nonExistRealm)",
NON_EXIST_MAPPER));
}
ServerReload.reloadIfRequired(managementClient);
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
cli.sendLine(String.format("/subsystem=elytron/constant-realm-mapper=%s:remove()",
DEFAULT_REALM_MAPPER));
cli.sendLine(String.format("/subsystem=elytron/constant-realm-mapper=%s:remove()",
REALM1_MAPPER));
cli.sendLine(String.format("/subsystem=elytron/constant-realm-mapper=%s:remove()",
REALM2_MAPPER));
cli.sendLine(String.format("/subsystem=elytron/constant-realm-mapper=%s:remove()",
NON_EXIST_MAPPER));
}
ServerReload.reloadIfRequired(managementClient);
}
}
}
| 6,391
| 47.793893
| 128
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realmmappers/RealmMapperServerSetupTask.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.wildfly.test.integration.elytron.realmmappers;
import java.util.ArrayList;
import java.util.List;
import org.wildfly.test.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
import org.wildfly.test.security.common.elytron.PropertiesRealm;
import org.wildfly.test.security.common.elytron.SimpleSecurityDomain;
import org.wildfly.test.security.common.elytron.UndertowDomainMapper;
import org.wildfly.test.security.servlets.SecuredPrincipalPrintingServlet;
/**
*
* @author olukas
*/
public class RealmMapperServerSetupTask extends AbstractElytronSetupTask {
public static final String USER_IN_DEFAULT_REALM = "userInDefaultRealm";
public static final String USER_IN_REALM1 = "userInRealm1";
public static final String USER_IN_REALM2 = "userInRealm2";
public static final String USER_IN_REALM3 = "userInRealm3";
public static final String USER_IN_DEFAULT_REALM_MAPPED = "userInDefaultRealm&mapped";
public static final String USER_IN_DEFAULT_REALM_MAPPED2 = "userInDefaultRealm@mapped2";
public static final String USER_IN_REALM1_WITH_REALM = "userInRealm1@realm1";
public static final String USER_IN_REALM1_WITH_REALM_AND_SUFFIX = "userInRealm1@realm1&suffix";
public static final String USER_IN_REALM1_WITH_INFIX_AND_SUFFIX = "userInRealm1@infix&suffix";
public static final String USER_IN_REALM1_WITH_REALM_AND_DIFFERENT_SUFFIX = "userInRealm1@realm1&different";
public static final String USER_IN_REALM2_WITH_REALM1 = "userInRealm2&realm1";
public static final String CORRECT_PASSWORD = "password";
public static final String SECURITY_DOMAIN_NAME = "constantRealmMapperSecurityDomain";
public static final String SECURITY_DOMAIN_REFERENCE = "usedSecurityDomain";
public static final String DEFAULT_REALM = "defaultRealm";
public static final String REALM1 = "realm1";
public static final String REALM2 = "realm2";
public static final String REALM3 = "realm3";
@Override
protected ConfigurableElement[] getConfigurableElements() {
List<ConfigurableElement> elements = new ArrayList<>();
elements.add(PropertiesRealm.builder().withName(DEFAULT_REALM)
.withUser(USER_IN_DEFAULT_REALM, CORRECT_PASSWORD, SecuredPrincipalPrintingServlet.ALLOWED_ROLE)
.withUser(USER_IN_DEFAULT_REALM_MAPPED, CORRECT_PASSWORD, SecuredPrincipalPrintingServlet.ALLOWED_ROLE)
.withUser(USER_IN_DEFAULT_REALM_MAPPED2, CORRECT_PASSWORD, SecuredPrincipalPrintingServlet.ALLOWED_ROLE)
.build());
elements.add(PropertiesRealm.builder().withName(REALM1)
.withUser(USER_IN_REALM1, CORRECT_PASSWORD, SecuredPrincipalPrintingServlet.ALLOWED_ROLE)
.withUser(USER_IN_REALM1_WITH_REALM, CORRECT_PASSWORD, SecuredPrincipalPrintingServlet.ALLOWED_ROLE)
.withUser(USER_IN_REALM1_WITH_REALM_AND_SUFFIX, CORRECT_PASSWORD, SecuredPrincipalPrintingServlet.ALLOWED_ROLE)
.withUser(USER_IN_REALM1_WITH_INFIX_AND_SUFFIX, CORRECT_PASSWORD, SecuredPrincipalPrintingServlet.ALLOWED_ROLE)
.withUser(USER_IN_REALM1_WITH_REALM_AND_DIFFERENT_SUFFIX, CORRECT_PASSWORD, SecuredPrincipalPrintingServlet.ALLOWED_ROLE)
.build());
elements.add(PropertiesRealm.builder().withName(REALM2)
.withUser(USER_IN_REALM2, CORRECT_PASSWORD, SecuredPrincipalPrintingServlet.ALLOWED_ROLE)
.withUser(USER_IN_REALM2_WITH_REALM1, CORRECT_PASSWORD, SecuredPrincipalPrintingServlet.ALLOWED_ROLE)
.build());
elements.add(PropertiesRealm.builder().withName(REALM3)
.withUser(USER_IN_REALM3, CORRECT_PASSWORD, SecuredPrincipalPrintingServlet.ALLOWED_ROLE).build());
SimpleSecurityDomain.SecurityDomainRealm sdDefaultRealm = SimpleSecurityDomain.SecurityDomainRealm.builder().withRoleDecoder("groups-to-roles")
.withRealm(DEFAULT_REALM).build();
SimpleSecurityDomain.SecurityDomainRealm sdRealm1 = SimpleSecurityDomain.SecurityDomainRealm.builder().withRoleDecoder("groups-to-roles")
.withRealm(REALM1).build();
SimpleSecurityDomain.SecurityDomainRealm sdRealm2 = SimpleSecurityDomain.SecurityDomainRealm.builder().withRoleDecoder("groups-to-roles")
.withRealm(REALM2).build();
SimpleSecurityDomain.SecurityDomainRealm sdRealm3 = SimpleSecurityDomain.SecurityDomainRealm.builder().withRoleDecoder("groups-to-roles")
.withRealm(REALM3).build();
elements.add(SimpleSecurityDomain.builder().withName(SECURITY_DOMAIN_NAME).withDefaultRealm(DEFAULT_REALM)
.withPermissionMapper("default-permission-mapper").withRealms(sdDefaultRealm, sdRealm1, sdRealm2, sdRealm3)
.build());
elements.add(UndertowDomainMapper.builder().withName(SECURITY_DOMAIN_NAME)
.withApplicationDomains(SECURITY_DOMAIN_REFERENCE)
.build());
return elements.toArray(new ConfigurableElement[elements.size()]);
}
}
| 6,148
| 57.009434
| 151
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/sasl/DefaultSaslConfigTestCase.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
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.sasl;
import java.util.ArrayList;
import java.util.List;
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.management.util.CLIWrapper;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.security.auth.client.AuthenticationConfiguration;
import org.wildfly.security.auth.client.AuthenticationContext;
import org.wildfly.security.auth.client.MatchRule;
import org.wildfly.security.sasl.SaslMechanismSelector;
import org.wildfly.test.integration.elytron.sasl.AbstractSaslTestBase.JmsSetup;
import org.wildfly.test.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
import org.wildfly.test.security.common.elytron.ConstantRoleMapper;
import org.wildfly.test.security.common.other.SimpleRemotingConnector;
import org.wildfly.test.security.common.other.SimpleSocketBinding;
/**
* Elytron SASL mechanisms tests which use Naming + JMS client. The server setup adds for each tested SASL configuration a new
* native remoting port and client tests functionality against it.
*
* @author Josef Cacek
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ JmsSetup.class, DefaultSaslConfigTestCase.ServerSetup.class })
public class DefaultSaslConfigTestCase extends AbstractSaslTestBase {
private static final String DEFAULT_SASL_AUTHENTICATION = "application-sasl-authentication";
private static final String DEFAULT = "DEFAULT";
private static final int PORT_DEFAULT = 10568;
/**
* Tests that ANONYMOUS SASL mechanism can't be used for authentication in default server configuration.
*/
@Test
public void testAnonymousFailsInDefault() throws Exception {
// Anonymous not supported in the default configuration
AuthenticationContext.empty()
.with(MatchRule.ALL,
AuthenticationConfiguration.empty()
.setSaslMechanismSelector(SaslMechanismSelector.fromString("ANONYMOUS")).useAnonymous())
.run(() -> sendAndReceiveMsg(PORT_DEFAULT, true));
}
/**
* Tests that JBOSS-LOCAL-USER SASL mechanism can be used for authentication in default server configuration.
*/
@Test
@Ignore("WFLY-8961")
public void testJBossLocalInDefault() throws Exception {
AuthenticationContext.empty()
.with(MatchRule.ALL,
AuthenticationConfiguration.empty()
.setSaslMechanismSelector(SaslMechanismSelector.fromString("JBOSS-LOCAL-USER")))
.run(() -> sendAndReceiveMsg(PORT_DEFAULT, false));
}
/**
* Tests that DIGEST-MD5 SASL mechanism can be used for authentication in default server configuration.
*/
@Test
public void testDigestInDefault() throws Exception {
AuthenticationContext.empty()
.with(MatchRule.ALL,
AuthenticationConfiguration.empty()
.setSaslMechanismSelector(SaslMechanismSelector.fromString("DIGEST-MD5")).useName("guest")
.usePassword("guest"))
.run(() -> sendAndReceiveMsg(PORT_DEFAULT, false, "guest", "guest"));
}
/**
* Setup task which configures remoting connectors for this test.
*/
public static class ServerSetup extends AbstractElytronSetupTask {
@Override
protected ConfigurableElement[] getConfigurableElements() {
List<ConfigurableElement> elements = new ArrayList<>();
// let all the authenticated users has the guest role
elements.add(ConstantRoleMapper.builder().withName("guest").withRoles("guest").build());
elements.add(new ConfigurableElement() {
@Override
public void create(CLIWrapper cli) throws Exception {
cli.sendLine("/subsystem=elytron/security-domain=ApplicationDomain:write-attribute(name=role-mapper, value=guest)");
}
@Override
public void remove(CLIWrapper cli) throws Exception {
cli.sendLine("/subsystem=elytron/security-domain=ApplicationDomain:write-attribute(name=role-mapper)");
}
@Override
public String getName() {
return "Configure role-mapper";
}
});
elements.add(SimpleSocketBinding.builder().withName(DEFAULT).withPort(PORT_DEFAULT).build());
elements.add(SimpleRemotingConnector.builder().withName(DEFAULT).withSocketBinding(DEFAULT)
.withSaslAuthenticationFactory(DEFAULT_SASL_AUTHENTICATION).build());
return elements.toArray(new ConfigurableElement[elements.size()]);
}
}
}
| 6,026
| 42.992701
| 136
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/sasl/OtpSaslTestCase.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
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.sasl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.List;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import jakarta.xml.bind.DatatypeConverter;
import org.apache.commons.io.FileUtils;
import org.apache.directory.server.annotations.CreateLdapServer;
import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.core.annotations.AnnotationUtils;
import org.apache.directory.server.core.annotations.CreateDS;
import org.apache.directory.server.core.annotations.CreatePartition;
import org.apache.directory.server.core.api.DirectoryService;
import org.apache.directory.server.core.factory.DSAnnotationProcessor;
import org.apache.directory.server.factory.ServerAnnotationProcessor;
import org.apache.directory.server.ldap.LdapServer;
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.network.NetworkUtils;
import org.jboss.as.test.integration.ldap.InMemoryDirectoryServiceFactory;
import org.jboss.as.test.integration.management.util.CLIWrapper;
import org.jboss.as.test.integration.security.common.ManagedCreateLdapServer;
import org.jboss.as.test.integration.security.common.Utils;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.security.auth.client.AuthenticationConfiguration;
import org.wildfly.security.auth.client.AuthenticationContext;
import org.wildfly.security.auth.client.MatchRule;
import org.wildfly.security.auth.permission.LoginPermission;
import org.wildfly.security.sasl.SaslMechanismSelector;
import org.wildfly.test.integration.elytron.sasl.AbstractSaslTestBase.JmsSetup;
import org.wildfly.test.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
import org.wildfly.test.security.common.elytron.ConstantPermissionMapper;
import org.wildfly.test.security.common.elytron.MechanismConfiguration;
import org.wildfly.test.security.common.elytron.PermissionRef;
import org.wildfly.test.security.common.elytron.SimpleSaslAuthenticationFactory;
import org.wildfly.test.security.common.elytron.SimpleSecurityDomain;
import org.wildfly.test.security.common.elytron.SimpleSecurityDomain.SecurityDomainRealm;
import org.wildfly.test.security.common.other.MessagingElytronDomainConfigurator;
import org.wildfly.test.security.common.other.SimpleRemotingConnector;
import org.wildfly.test.security.common.other.SimpleSocketBinding;
/**
* Elytron OTP SASL mechanism tests which use Naming + JMS client. The server setup adds for each tested SASL configuration a
* new native remoting port and client tests functionality against it.
*
* @author Josef Cacek
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ JmsSetup.class, OtpSaslTestCase.ServerSetup.class })
@Ignore("WFLY-8667")
public class OtpSaslTestCase extends AbstractSaslTestBase {
private static final String OTP = "OTP";
private static final String OTP_ALGORITHM = "otp-sha1";
private static final String OTP_PASSPHRASE = "This is a test.";
// https://www.ocf.berkeley.edu/~jjlin/jsotp/
// http://tomeko.net/online_tools/hex_to_base64.php?lang=en
private static final byte[] OTP_HASH_99 = DatatypeConverter.parseHexBinary("87FEC7768B73CCF9");
private static final byte[] OTP_HASH_98 = DatatypeConverter.parseHexBinary("33D865A2BF9E5E76");
private static final int PORT_OTP = 10569;
private static final int LDAP_PORT = 10389;
private static final String HOST = Utils.getDefaultHost(false);
private static final String HOST_FMT = NetworkUtils.formatPossibleIpv6Address(HOST);
private static final String LDAP_URL = "ldap://" + HOST_FMT + ":" + LDAP_PORT;
/**
* Tests that client is able to use OTP SASL mechanism when server allows it.
*/
@Test
public void testOtpAccess() throws Exception {
assertSequenceAndHash(99, OTP_HASH_99);
Runnable runAndExpectFail = () -> sendAndReceiveMsg(PORT_OTP, true);
AuthenticationContext.empty()
.with(MatchRule.ALL,
AuthenticationConfiguration.empty()
.setSaslMechanismSelector(SaslMechanismSelector.fromString(OTP)))
.run(runAndExpectFail);
assertSequenceAndHash(99, OTP_HASH_99);
AuthenticationContext.empty().with(MatchRule.ALL,
AuthenticationConfiguration.empty()
.setSaslMechanismSelector(SaslMechanismSelector.fromString(OTP)).useName("jduke").usePassword("TeSt"))
.run(runAndExpectFail);
assertSequenceAndHash(99, OTP_HASH_99);
AuthenticationContext.empty()
.with(MatchRule.ALL,
AuthenticationConfiguration.empty()
.setSaslMechanismSelector(SaslMechanismSelector.fromString(OTP)).useName("jduke")
.usePassword(OTP_PASSPHRASE))
.run(() -> sendAndReceiveMsg(PORT_OTP, false));
assertSequenceAndHash(98, OTP_HASH_98);
}
/**
* Check correct user attribute values in the LDAP when using OTP algorithm.
*/
private void assertSequenceAndHash(Integer expectedSequence, byte[] expectedHash) throws NamingException {
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, LDAP_URL);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
env.put(Context.SECURITY_CREDENTIALS, "secret");
final LdapContext ctx = new InitialLdapContext(env, null);
NamingEnumeration<?> namingEnum = ctx.search("dc=wildfly,dc=org", new BasicAttributes("cn", "jduke"));
if (namingEnum.hasMore()) {
SearchResult sr = (SearchResult) namingEnum.next();
Attributes attrs = sr.getAttributes();
assertEquals("Unexpected sequence number in LDAP attribute", expectedSequence,
new Integer(attrs.get("telephoneNumber").get().toString()));
assertEquals("Unexpected hash value in LDAP attribute", Base64.getEncoder().encodeToString(expectedHash),
attrs.get("title").get().toString());
} else {
fail("User not found in LDAP");
}
namingEnum.close();
ctx.close();
}
/**
* Setup task which configures Elytron security domains and remoting connectors for this test.
*/
public static class ServerSetup extends AbstractElytronSetupTask {
@Override
protected ConfigurableElement[] getConfigurableElements() {
List<ConfigurableElement> elements = new ArrayList<>();
elements.add(ConstantPermissionMapper.builder().withName(NAME)
.withPermissions(PermissionRef.fromPermission(new LoginPermission())).build());
elements.add(new OtpLdapConf());
elements.add(SimpleSecurityDomain.builder().withName(OTP).withDefaultRealm(OTP).withPermissionMapper(NAME)
.withRealms(SecurityDomainRealm.builder().withRealm(OTP).withRoleDecoder("groups-to-roles").build())
.build());
elements.add(MessagingElytronDomainConfigurator.builder().withElytronDomain(OTP).build());
elements.add(SimpleSaslAuthenticationFactory.builder().withName(OTP).withSaslServerFactory("elytron")
.withSecurityDomain(OTP)
.addMechanismConfiguration(MechanismConfiguration.builder().withMechanismName(OTP).build()).build());
elements.add(SimpleSocketBinding.builder().withName(OTP).withPort(PORT_OTP).build());
elements.add(SimpleRemotingConnector.builder().withName(OTP).withSocketBinding(OTP)
.withSaslAuthenticationFactory(OTP).build());
return elements.toArray(new ConfigurableElement[elements.size()]);
}
/**
* LDAP configurable element - set's and starts LDAP instance and configures ldap-realm in the Elytron. The LDAP realm
* is used as modifiable realm for testing OTP SASL mechanism.
*/
//@formatter:off
@CreateDS(
name = "WildFlyDS",
factory = InMemoryDirectoryServiceFactory.class,
partitions = @CreatePartition(name = "wildfly", suffix = "dc=wildfly,dc=org"),
allowAnonAccess = true
)
@CreateLdapServer(
transports = @CreateTransport(protocol = "LDAP", address = "localhost", port = LDAP_PORT),
allowAnonymousAccess = true
)
//@formatter:on
private static class OtpLdapConf implements ConfigurableElement {
private static DirectoryService directoryService;
private static LdapServer ldapServer;
@Override
public void create(CLIWrapper cli) throws Exception {
Encoder b64e = Base64.getEncoder();
directoryService = DSAnnotationProcessor.getDirectoryService();
DSAnnotationProcessor.injectEntries(directoryService,
"dn: dc=wildfly,dc=org\n" //
+ "dc: jboss\n" //
+ "objectClass: top\n" //
+ "objectClass: domain\n" //
+ "\n" //
+ "dn: cn=jduke,dc=wildfly,dc=org\n" //
+ "objectclass: top\n" //
+ "objectclass: person\n" //
+ "objectclass: organizationalPerson\n" //
+ "cn: jduke\n" //
+ "sn: guest\n" // role ;)
+ "street: " + OTP_ALGORITHM + "\n" // algorithm
+ "title: " + b64e.encodeToString(OTP_HASH_99) + "\n" // stored hash
+ "description: TeSt\n" // seed
+ "telephoneNumber: 99\n" // sequence
);
final ManagedCreateLdapServer createLdapServer = new ManagedCreateLdapServer(
(CreateLdapServer) AnnotationUtils.getInstance(CreateLdapServer.class));
Utils.fixApacheDSTransportAddress(createLdapServer, Utils.getSecondaryTestAddress(null, false));
ldapServer = ServerAnnotationProcessor.instantiateLdapServer(createLdapServer, directoryService);
ldapServer.start();
cli.sendLine(String.format(
"/subsystem=elytron/dir-context=%s:add(url=\"%s\",principal=\"uid=admin,ou=system\",credential-reference={clear-text=secret})",
OTP, LDAP_URL));
cli.sendLine(String
.format("/subsystem=elytron/ldap-realm=%s:add(dir-context=%s,identity-mapping={rdn-identifier=cn,search-base-dn=\"dc=wildfly,dc=org\","
+ "otp-credential-mapper={algorithm-from=street, hash-from=title, seed-from=description, sequence-from=telephoneNumber},"
+ "attribute-mapping=[{from=sn,to=groups}]})", OTP, OTP));
}
@Override
public void remove(CLIWrapper cli) throws Exception {
// cli.sendLine(String.format("/subsystem=elytron/security-domain=%s:remove()", OTP));
cli.sendLine(String.format("/subsystem=elytron/ldap-realm=%s:remove()", OTP));
cli.sendLine(String.format("/subsystem=elytron/dir-context=%s:remove()", OTP));
ldapServer.stop();
directoryService.shutdown();
FileUtils.deleteDirectory(directoryService.getInstanceLayout().getInstanceDirectory());
}
@Override
public String getName() {
return "ldap-configuration";
}
}
}
}
| 13,646
| 49.357934
| 159
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/sasl/AnonymousSaslMechTestCase.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
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.sasl;
import java.util.ArrayList;
import java.util.List;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.security.auth.client.AuthenticationConfiguration;
import org.wildfly.security.auth.client.AuthenticationContext;
import org.wildfly.security.auth.client.MatchRule;
import org.wildfly.security.auth.permission.LoginPermission;
import org.wildfly.security.sasl.SaslMechanismSelector;
import org.wildfly.test.integration.elytron.sasl.AbstractSaslTestBase.JmsSetup;
import org.wildfly.test.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
import org.wildfly.test.security.common.elytron.ConstantPermissionMapper;
import org.wildfly.test.security.common.elytron.ConstantRoleMapper;
import org.wildfly.test.security.common.elytron.MechanismConfiguration;
import org.wildfly.test.security.common.elytron.PermissionRef;
import org.wildfly.test.security.common.elytron.SaslFilter;
import org.wildfly.test.security.common.elytron.SimpleConfigurableSaslServerFactory;
import org.wildfly.test.security.common.elytron.SimpleSaslAuthenticationFactory;
import org.wildfly.test.security.common.elytron.SimpleSecurityDomain;
import org.wildfly.test.security.common.elytron.SimpleSecurityDomain.SecurityDomainRealm;
import org.wildfly.test.security.common.other.MessagingElytronDomainConfigurator;
import org.wildfly.test.security.common.other.SimpleRemotingConnector;
import org.wildfly.test.security.common.other.SimpleSocketBinding;
/**
* Elytron SASL mechanisms tests which use Naming + JMS client. The server setup adds for each tested SASL configuration a new
* native remoting port and client tests functionality against it.
*
* @author Josef Cacek
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ JmsSetup.class, AnonymousSaslMechTestCase.ServerSetup.class })
public class AnonymousSaslMechTestCase extends AbstractSaslTestBase {
private static final String ANONYMOUS = "ANONYMOUS";
private static final int PORT_ANONYMOUS = 10567;
/**
* Tests that client is able to use ANONYMOUS SASL mechanism when server allows it.
*/
@Test
public void testAnonymousAccess() throws Exception {
AuthenticationContext.empty()
.with(MatchRule.ALL,
AuthenticationConfiguration.empty()
.setSaslMechanismSelector(SaslMechanismSelector.fromString(ANONYMOUS)))
.run(() -> sendAndReceiveMsg(PORT_ANONYMOUS, false));
}
/**
* Setup task which configures Elytron security domains and remoting connectors for this test.
*/
public static class ServerSetup extends AbstractElytronSetupTask {
@Override
protected ConfigurableElement[] getConfigurableElements() {
List<ConfigurableElement> elements = new ArrayList<>();
elements.add(ConstantPermissionMapper.builder().withName(NAME)
.withPermissions(PermissionRef.fromPermission(new LoginPermission())).build());
elements.add(ConstantRoleMapper.builder().withName(NAME).withRoles("guest").build());
elements.add(SimpleSecurityDomain.builder().withName(NAME).withDefaultRealm("ApplicationRealm").withRoleMapper(NAME)
.withPermissionMapper(NAME).withRealms(SecurityDomainRealm.builder().withRealm("ApplicationRealm").build())
.build());
elements.add(SimpleConfigurableSaslServerFactory.builder().withName(ANONYMOUS).withSaslServerFactory("elytron")
.addFilter(SaslFilter.builder().withPatternFilter(ANONYMOUS).build()).build());
elements.add(SimpleSaslAuthenticationFactory.builder().withName(ANONYMOUS).withSaslServerFactory(ANONYMOUS)
.withSecurityDomain(NAME)
.addMechanismConfiguration(MechanismConfiguration.builder().withMechanismName(ANONYMOUS).build()).build());
elements.add(MessagingElytronDomainConfigurator.builder().withElytronDomain(NAME).build());
elements.add(SimpleSocketBinding.builder().withName(ANONYMOUS).withPort(PORT_ANONYMOUS).build());
elements.add(SimpleRemotingConnector.builder().withName(ANONYMOUS).withSocketBinding(ANONYMOUS)
.withSaslAuthenticationFactory(ANONYMOUS).build());
return elements.toArray(new ConfigurableElement[elements.size()]);
}
}
}
| 5,660
| 49.544643
| 128
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/sasl/AbstractSaslTestBase.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
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.sasl;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Properties;
import jakarta.jms.ConnectionFactory;
import jakarta.jms.Destination;
import jakarta.jms.JMSConsumer;
import jakarta.jms.JMSContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.security.sasl.SaslException;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.network.NetworkUtils;
import org.jboss.as.test.integration.common.jms.ActiveMQProviderJMSOperations;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.shared.TimeoutUtil;
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.Assert;
import org.wildfly.naming.client.WildFlyInitialContextFactory;
/**
* Abstract parent for JMS client based SASL mechanisms tests.
*
* @author Josef Cacek
*/
public abstract class AbstractSaslTestBase {
private static Logger LOGGER = Logger.getLogger(AbstractSaslTestBase.class);
protected static final String NAME = AbstractSaslTestBase.class.getSimpleName();
protected static final String JNDI_QUEUE_NAME = "java:jboss/exported/" + NAME;
protected static final String MESSAGE = "Hello, World!";
protected static final String CONNECTION_FACTORY = "jms/RemoteConnectionFactory";
protected static final String HOST = Utils.getDefaultHost(false);
protected static final String HOST_FMT = NetworkUtils.formatPossibleIpv6Address(HOST);
@Deployment(testable = false)
public static WebArchive dummyDeployment() {
return ShrinkWrap.create(WebArchive.class, NAME + ".war").addAsWebResource(new StringAsset("Test"), "index.html");
}
protected void sendAndReceiveMsg(int remotingPort, boolean expectedSaslFail) {
sendAndReceiveMsg(remotingPort, expectedSaslFail, null, null);
}
protected void sendAndReceiveMsg(int remotingPort, boolean expectedSaslFail, String username, String password) {
Context namingContext = null;
try {
// Set up the namingContext for the JNDI lookup
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, WildFlyInitialContextFactory.class.getName());
env.put("remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "false");
env.put(Context.PROVIDER_URL, "remote://" + HOST_FMT + ":" + remotingPort);
namingContext = new InitialContext(env);
// Perform the JNDI lookups
ConnectionFactory connectionFactory = null;
try {
connectionFactory = (ConnectionFactory) namingContext.lookup(CONNECTION_FACTORY);
assertFalse("JNDI lookup should have failed.", expectedSaslFail);
} catch (NamingException e) {
if (expectedSaslFail) {
// only SASL failures are expected
assertTrue("Unexpected cause of lookup failure", e.getCause() instanceof SaslException);
return;
}
throw e;
}
Destination destination = (Destination) namingContext.lookup(NAME);
try (JMSContext context = (username != null ? connectionFactory.createContext(username, password)
: connectionFactory.createContext())) {
// Send a message
context.createProducer().send(destination, MESSAGE);
// Create the JMS consumer
JMSConsumer consumer = context.createConsumer(destination);
// Then receive the same message that was sent
String text = consumer.receiveBody(String.class, TimeoutUtil.adjust(5000));
Assert.assertEquals(MESSAGE, text);
}
} catch (NamingException e) {
LOGGER.error("Naming problem occured.", e);
throw new RuntimeException(e);
} finally {
if (namingContext != null) {
try {
namingContext.close();
} catch (NamingException e) {
LOGGER.error("Naming problem occured during closing context.", e);
}
}
}
}
/**
* Setup task which configures test queue in the messaging subsystem.
*/
public static class JmsSetup implements ServerSetupTask {
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
new ActiveMQProviderJMSOperations(managementClient).createJmsQueue(NAME, JNDI_QUEUE_NAME);
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
new ActiveMQProviderJMSOperations(managementClient).removeJmsQueue(NAME);
}
}
}
| 6,220
| 40.473333
| 122
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/roledecoders/SimpleRoleDecoderTestCase.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.wildfly.test.integration.elytron.roledecoders;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static jakarta.servlet.http.HttpServletResponse.SC_FORBIDDEN;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.codehaus.plexus.util.StringUtils;
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.arquillian.container.ManagementClient;
import org.jboss.as.test.integration.management.util.CLIWrapper;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.RolePrintingServlet;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import static org.junit.Assert.fail;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.test.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
import org.wildfly.test.security.common.elytron.PropertiesRealm;
import org.wildfly.test.security.common.elytron.SimpleSecurityDomain;
import org.wildfly.test.security.common.elytron.UndertowDomainMapper;
/**
* Test case for Elytron Simple Role Decoder.
*
* @author olukas
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({SimpleRoleDecoderTestCase.SetupTask.class})
public class SimpleRoleDecoderTestCase {
private static final String DECODE_FROM_ROLE_ATTRIBUTE_A = "decode-from-role-attribute-a";
private static final String DECODE_FROM_ROLE_ATTRIBUTE_B = "decode-from-role-attribute-b";
private static final String USER_WITH_ONE_ROLE = "userWithOneRole";
private static final String USER_WITH_TWO_ROLES = "userWithTwoRoles";
private static final String PASSWORD = "password";
private static final String ROLE1 = "role1";
private static final String ROLE2 = "role2";
static final String[] ALL_TESTED_ROLES = {ROLE1, ROLE2};
static final String QUERY_ROLES;
static {
final List<NameValuePair> qparams = new ArrayList<>();
for (final String role : ALL_TESTED_ROLES) {
qparams.add(new BasicNameValuePair(RolePrintingServlet.PARAM_ROLE_NAME, role));
}
QUERY_ROLES = URLEncodedUtils.format(qparams, StandardCharsets.UTF_8);
}
@Deployment(name = DECODE_FROM_ROLE_ATTRIBUTE_A)
public static WebArchive deploymentDecodeFromAttributeA() {
return deployment(DECODE_FROM_ROLE_ATTRIBUTE_A);
}
@Deployment(name = DECODE_FROM_ROLE_ATTRIBUTE_B)
public static WebArchive deploymentDecodeFromAttributeB() {
return deployment(DECODE_FROM_ROLE_ATTRIBUTE_B);
}
private static WebArchive deployment(String name) {
final WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war");
war.addClasses(RolePrintingServlet.class);
war.addAsWebInfResource(SimpleRoleDecoderTestCase.class.getPackage(), "simple-role-decoder-web.xml", "web.xml");
war.addAsWebInfResource(Utils.getJBossWebXmlAsset(name), "jboss-web.xml");
return war;
}
/**
* Test whether role is decoded correctly from attribute which includes one value.
*/
@Test
@OperateOnDeployment(DECODE_FROM_ROLE_ATTRIBUTE_A)
public void testDecodeOneRole(@ArquillianResource URL webAppURL) throws Exception {
testAssignedRoles(webAppURL, USER_WITH_ONE_ROLE, PASSWORD, ROLE1);
}
/**
* Test whether both roles are decoded correctly from attribute which includes two values.
*/
@Test
@OperateOnDeployment(DECODE_FROM_ROLE_ATTRIBUTE_A)
public void testDecodeMoreRoles(@ArquillianResource URL webAppURL) throws Exception {
testAssignedRoles(webAppURL, USER_WITH_TWO_ROLES, PASSWORD, ROLE1, ROLE2);
}
/**
* Test whether no role is decoded when they are included in different attribute.
*/
@Test
@OperateOnDeployment(DECODE_FROM_ROLE_ATTRIBUTE_B)
public void testDoNotDecodeRoleFromDifferentAttribute(@ArquillianResource URL webAppURL) throws Exception {
assertNoRoleAssigned(webAppURL, USER_WITH_TWO_ROLES, PASSWORD);
}
private void testAssignedRoles(URL webAppURL, String username, String password, String... assignedRoles) throws Exception {
final URL rolesPrintingURL = prepareRolesPrintingURL(webAppURL);
final String rolesResponse = Utils.makeCallWithBasicAuthn(rolesPrintingURL, username, password, SC_OK);
final List<String> assignedRolesList = Arrays.asList(assignedRoles);
for (String role : ALL_TESTED_ROLES) {
if (assignedRolesList.contains(role)) {
assertInRole(rolesResponse, role);
} else {
assertNotInRole(rolesResponse, role);
}
}
}
private void assertNoRoleAssigned(URL webAppURL, String username, String password) throws Exception {
final URL rolesPrintingURL = prepareRolesPrintingURL(webAppURL);
Utils.makeCallWithBasicAuthn(rolesPrintingURL, username, password, SC_FORBIDDEN);
}
private URL prepareRolesPrintingURL(URL webAppURL) throws MalformedURLException {
return new URL(webAppURL.toExternalForm() + RolePrintingServlet.SERVLET_PATH.substring(1) + "?" + QUERY_ROLES);
}
private void assertInRole(final String rolePrintResponse, String role) {
if (!StringUtils.contains(rolePrintResponse, "," + role + ",")) {
fail("Missing role '" + role + "' assignment");
}
}
private void assertNotInRole(final String rolePrintResponse, String role) {
if (StringUtils.contains(rolePrintResponse, "," + role + ",")) {
fail("Unexpected role '" + role + "' assignment");
}
}
static class SetupTask extends AbstractElytronSetupTask {
private static final String PROPERTIES_REALM = "simple-role-decoder-properties-realm";
private static final String ROLE_ATTRIBUTE_A = "role-attribute-a";
private static final String ROLE_ATTRIBUTE_B = "role-attribute-b";
@Override
public void setup(ManagementClient mc, String string) throws Exception {
try (CLIWrapper cli = new CLIWrapper(true)) {
cli.sendLine(String.format(
"/subsystem=elytron/simple-role-decoder=%s:add(attribute=%s)",
DECODE_FROM_ROLE_ATTRIBUTE_A, ROLE_ATTRIBUTE_A));
cli.sendLine(String.format(
"/subsystem=elytron/simple-role-decoder=%s:add(attribute=%s)",
DECODE_FROM_ROLE_ATTRIBUTE_B, ROLE_ATTRIBUTE_B));
}
super.setup(mc, string);
}
@Override
public void tearDown(ManagementClient mc, String string) throws Exception {
super.tearDown(mc, string);
try (CLIWrapper cli = new CLIWrapper(true)) {
cli.sendLine(String.format("/subsystem=elytron/simple-role-decoder=%s:remove()", DECODE_FROM_ROLE_ATTRIBUTE_B));
cli.sendLine(String.format("/subsystem=elytron/simple-role-decoder=%s:remove()", DECODE_FROM_ROLE_ATTRIBUTE_A));
}
ServerReload.reloadIfRequired(mc);
}
@Override
protected ConfigurableElement[] getConfigurableElements() {
List<ConfigurableElement> elements = new ArrayList<>();
elements.add(PropertiesRealm.builder().withName(PROPERTIES_REALM)
.withGroupsAttribute(ROLE_ATTRIBUTE_A)
.withUser(USER_WITH_ONE_ROLE, PASSWORD, ROLE1)
.withUser(USER_WITH_TWO_ROLES, PASSWORD, ROLE1, ROLE2)
.build());
addResourcesForAuthnWithSimpleRoleDecoder(elements, DECODE_FROM_ROLE_ATTRIBUTE_A, ROLE_ATTRIBUTE_A);
addResourcesForAuthnWithSimpleRoleDecoder(elements, DECODE_FROM_ROLE_ATTRIBUTE_B, ROLE_ATTRIBUTE_B);
return elements.toArray(new ConfigurableElement[elements.size()]);
}
private void addResourcesForAuthnWithSimpleRoleDecoder(List<ConfigurableElement> elements, String name, String attribute) {
elements.add(
SimpleSecurityDomain.builder().withName(name)
.withDefaultRealm(PROPERTIES_REALM)
.withPermissionMapper("default-permission-mapper")
.withRealms(SimpleSecurityDomain.SecurityDomainRealm
.builder()
.withRealm(PROPERTIES_REALM)
.withRoleDecoder(name)
.build())
.build());
elements.add(UndertowDomainMapper.builder()
.withName(name)
.withApplicationDomains(name)
.build());
}
}
}
| 10,406
| 43.285106
| 131
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/http/SpnegoMechTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.http;
import static org.apache.http.HttpStatus.SC_OK;
import static org.apache.http.HttpStatus.SC_UNAUTHORIZED;
import static org.jboss.as.test.shared.CliUtils.asAbsolutePath;
import static org.junit.Assert.assertEquals;
import static org.wildfly.security.auth.util.GSSCredentialSecurityFactory.KERBEROS_V5;
import static org.wildfly.security.auth.util.GSSCredentialSecurityFactory.SPNEGO;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.kerberos.KerberosPrincipal;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import org.apache.commons.io.FileUtils;
import org.apache.directory.api.ldap.model.entry.DefaultEntry;
import org.apache.directory.api.ldap.model.ldif.LdifEntry;
import org.apache.directory.api.ldap.model.ldif.LdifReader;
import org.apache.directory.api.ldap.model.schema.SchemaManager;
import org.apache.directory.server.annotations.CreateKdcServer;
import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.core.annotations.ContextEntry;
import org.apache.directory.server.core.annotations.CreateDS;
import org.apache.directory.server.core.annotations.CreatePartition;
import org.apache.directory.server.core.api.DirectoryService;
import org.apache.directory.server.core.factory.DSAnnotationProcessor;
import org.apache.directory.server.core.kerberos.KeyDerivationInterceptor;
import org.apache.directory.server.kerberos.kdc.KdcServer;
import org.apache.directory.server.kerberos.shared.crypto.encryption.KerberosKeyFactory;
import org.apache.directory.server.kerberos.shared.keytab.Keytab;
import org.apache.directory.server.kerberos.shared.keytab.KeytabEntry;
import org.apache.directory.shared.kerberos.KerberosTime;
import org.apache.directory.shared.kerberos.codec.types.EncryptionType;
import org.apache.directory.shared.kerberos.components.EncryptionKey;
import org.apache.http.client.methods.CloseableHttpResponse;
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.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.GSSName;
import org.ietf.jgss.Oid;
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.test.integration.management.util.CLIWrapper;
import org.jboss.as.test.integration.security.common.AbstractSystemPropertiesServerSetupTask;
import org.jboss.as.test.integration.security.common.KDCServerAnnotationProcessor;
import org.jboss.as.test.integration.security.common.Krb5LoginConfiguration;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.SimpleServlet;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
import org.wildfly.test.security.common.elytron.MechanismConfiguration;
import org.wildfly.test.security.common.elytron.PropertiesRealm;
import org.wildfly.test.security.common.elytron.SimpleSecurityDomain;
/**
* Test of SPNEGO HTTP mechanism.
*
* @author Jan Kalina
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({
SpnegoMechTestCase.KDCServerSetupTask.class,
SpnegoMechTestCase.ServerSetup.class,
SpnegoMechTestCase.KerberosSystemPropertiesSetupTask.class
})
public class SpnegoMechTestCase extends AbstractMechTestBase {
private static final String NAME = SpnegoMechTestCase.class.getSimpleName();
private static final String HEADER_WWW_AUTHENTICATE = "WWW-Authenticate";
private static final String HEADER_AUTHORIZATION = "Authorization";
private static final String CHALLENGE_PREFIX = "Negotiate ";
private static final File KRB5_CONF = new File(SpnegoMechTestCase.class.getResource(NAME + "-krb5.conf").getFile());
private static final boolean DEBUG = false;
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, NAME + ".war")
.addClasses(SimpleServlet.class)
.addAsWebInfResource(Utils.getJBossWebXmlAsset(APP_DOMAIN), "jboss-web.xml")
.addAsWebInfResource(SpnegoMechTestCase.class.getPackage(), NAME + "-web.xml", "web.xml");
}
/**
* Setup system properties for client.
*/
@BeforeClass
public static void initProperties() {
System.setProperty("java.security.krb5.conf", KRB5_CONF.getAbsolutePath());
System.setProperty("sun.security.krb5.debug", Boolean.toString(DEBUG));
}
@Test
public void testSuccess() throws Exception {
final Krb5LoginConfiguration krb5Configuration = new Krb5LoginConfiguration(Utils.getLoginConfiguration());
Configuration.setConfiguration(krb5Configuration);
LoginContext lc = Utils.loginWithKerberos(krb5Configuration, "user1@WILDFLY.ORG", "password1");
Subject.doAs(lc.getSubject(), (PrivilegedExceptionAction<Void>) () -> {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
GSSManager manager = GSSManager.getInstance();
GSSName acceptorName = manager.createName("HTTP@localhost", GSSName.NT_HOSTBASED_SERVICE);
GSSCredential credential = manager.createCredential(null, GSSCredential.DEFAULT_LIFETIME, new Oid[] { KERBEROS_V5, SPNEGO }, GSSCredential.INITIATE_ONLY);
GSSContext context = manager.createContext(acceptorName, KERBEROS_V5, credential, GSSContext.INDEFINITE_LIFETIME);
URI uri = new URI(url.toExternalForm() + "role1");
byte[] message = new byte[0];
for (int i = 0; i < 5; i++) { // prevent infinite loop - max 5 continuations
message = context.initSecContext(message, 0, message.length);
HttpGet request = new HttpGet(uri);
request.setHeader(HEADER_AUTHORIZATION, CHALLENGE_PREFIX + Base64.getEncoder().encodeToString(message));
try ( CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != SC_UNAUTHORIZED) {
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", SimpleServlet.RESPONSE_BODY, EntityUtils.toString(response.getEntity()));
// test cached identity
HttpGet request2 = new HttpGet(uri);
try ( CloseableHttpResponse response2 = httpClient.execute(request2)) {
int statusCode2 = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode2);
assertEquals("Unexpected content of HTTP response.", SimpleServlet.RESPONSE_BODY, EntityUtils.toString(response2.getEntity()));
}
return null;
}
String responseHeader = response.getFirstHeader(HEADER_WWW_AUTHENTICATE).getValue();
if (!responseHeader.startsWith(CHALLENGE_PREFIX)) Assert.fail("Invalid authenticate header");
message = Base64.getDecoder().decode(responseHeader.substring(CHALLENGE_PREFIX.length()));
}
}
Assert.fail("Infinite unauthorized loop");
}
return null;
});
}
/**
* A setup task which configures and starts Kerberos KDC server.
*/
@CreateDS(
name = "JBossDS-SpnegoMechTestCase",
factory = org.jboss.as.test.integration.ldap.InMemoryDirectoryServiceFactory.class,
partitions = {
@CreatePartition(
name = "wildfly",
suffix = "dc=wildfly,dc=org",
contextEntry = @ContextEntry(
entryLdif = "dn: dc=wildfly,dc=org\n" +
"dc: wildfly\n" +
"objectClass: top\n" +
"objectClass: domain\n\n"))
},
additionalInterceptors = { KeyDerivationInterceptor.class })
@CreateKdcServer(
primaryRealm = "WILDFLY.ORG",
kdcPrincipal = "krbtgt/WILDFLY.ORG@WILDFLY.ORG",
searchBaseDn = "dc=wildfly,dc=org",
transports = {
@CreateTransport(protocol = "UDP", port = 6088)
})
static class KDCServerSetupTask implements ServerSetupTask {
private DirectoryService directoryService;
private KdcServer kdcServer;
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
directoryService = DSAnnotationProcessor.getDirectoryService();
final SchemaManager schemaManager = directoryService.getSchemaManager();
for (LdifEntry ldifEntry : new LdifReader(SpnegoMechTestCase.class.getResourceAsStream(NAME + ".ldif"))) {
directoryService.getAdminSession().add(new DefaultEntry(schemaManager, ldifEntry.getEntry()));
}
kdcServer = KDCServerAnnotationProcessor.getKdcServer(directoryService, 1024, "localhost");
System.out.println("Starting kerberos");
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
System.out.println("Stopping kerberos");
kdcServer.stop();
directoryService.shutdown();
FileUtils.deleteDirectory(directoryService.getInstanceLayout().getInstanceDirectory());
}
}
/**
* A setup task which configures application server to use Kerberos.
* Includes keytab file generating. Excludes system properties setting.
*/
static class ServerSetup extends AbstractMechTestBase.ServerSetup {
private static final String SERVER_PRINCIPAL = "HTTP/localhost@WILDFLY.ORG";
private static final String SERVER_KEY_TAB = NAME + ".keytab";
private static final File WORK_DIR = new File("target" + File.separatorChar + NAME);
private final File SERVER_KEY_TAB_FILE = new File(WORK_DIR, SERVER_KEY_TAB);
public ServerSetup() throws IOException {
FileUtils.deleteDirectory(WORK_DIR);
WORK_DIR.mkdirs();
generateKeyTab(SERVER_KEY_TAB_FILE, SERVER_PRINCIPAL, "httppwd");
}
@Override
protected ConfigurableElement[] getConfigurableElements() {
List<ConfigurableElement> elements = new ArrayList<>();
// create kerberos-security-factory
elements.add(new ConfigurableElement() {
@Override
public String getName() {
return "Create kerberos-security-factory";
}
@Override
public void create(CLIWrapper cli) throws Exception {
cli.sendLine("/subsystem=elytron/kerberos-security-factory=" + NAME + ":add(" +
"principal=\"" + SERVER_PRINCIPAL + "\", " +
"path=\"" + asAbsolutePath(SERVER_KEY_TAB_FILE) + "\", " +
"mechanism-names=[KRB5, SPNEGO], required=true, " +
"debug=" + Boolean.toString(DEBUG) + ")");
if (DEBUG) cli.sendLine("/subsystem=logging/logger=org.wildfly.security:add(level=TRACE)");
}
@Override
public void remove(CLIWrapper cli) throws Exception {
cli.sendLine("/subsystem=elytron/kerberos-security-factory=" + NAME + ":remove");
if (DEBUG) cli.sendLine("/subsystem=logging/logger=org.wildfly.security:remove");
}
});
// create properties-realm
elements.add(PropertiesRealm.builder().withName(NAME)
.withUser("user1@WILDFLY.ORG", "", "Role1")
.build());
// create security-domain
elements.add(SimpleSecurityDomain.builder().withName(NAME).withDefaultRealm(NAME)
.withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder().withRoleDecoder("groups-to-roles").withRealm(NAME).build())
.withPermissionMapper("default-permission-mapper").build());
Collections.addAll(elements, super.getConfigurableElements());
return elements.toArray(new ConfigurableElement[elements.size()]);
}
@Override
protected String getSecurityDomain() {
return NAME;
}
@Override
protected MechanismConfiguration getMechanismConfiguration() {
return MechanismConfiguration.builder()
.withMechanismName("SPNEGO")
.withCredentialSecurityFactory(NAME)
.build();
}
private void generateKeyTab(File keyTabFile, String... credentials) throws IOException {
List<KeytabEntry> entries = new ArrayList<>();
KerberosTime ktm = new KerberosTime();
for (int i = 0; i < credentials.length;) {
String principal = credentials[i++];
String password = credentials[i++];
for (Map.Entry<EncryptionType, EncryptionKey> keyEntry : KerberosKeyFactory.getKerberosKeys(principal, password).entrySet()) {
EncryptionKey key = keyEntry.getValue();
entries.add(new KeytabEntry(principal, KerberosPrincipal.KRB_NT_PRINCIPAL, ktm, (byte) key.getKeyVersion(), key));
}
}
Keytab keyTab = Keytab.getInstance();
keyTab.setEntries(entries);
keyTab.write(keyTabFile);
}
}
/**
* A setup task creating properties on application server.
*/
static class KerberosSystemPropertiesSetupTask extends AbstractSystemPropertiesServerSetupTask {
@Override
protected SystemProperty[] getSystemProperties() {
final Map<String, String> map = new HashMap<>();
map.put("java.security.krb5.conf", KRB5_CONF.getAbsolutePath());
map.put("sun.security.krb5.debug", Boolean.toString(DEBUG));
return mapToSystemProperties(map);
}
}
}
| 16,581
| 46.242165
| 170
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/http/MinimalDigestMechTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.http;
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.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.SimpleServlet;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
import org.wildfly.test.security.common.elytron.MechanismConfiguration;
/**
* Test of DIGEST HTTP mechanism using a direct reference to the security domain instead of an authentication factory.
*
* @author Jan Kalina
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ MinimalDigestMechTestCase.ServerSetup.class })
public class MinimalDigestMechTestCase extends PasswordMechTestBase {
private static final String NAME = MinimalDigestMechTestCase.class.getSimpleName();
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, NAME + ".war")
.addClasses(SimpleServlet.class)
.addAsWebInfResource(Utils.getJBossWebXmlAsset(APP_DOMAIN), "jboss-web.xml")
.addAsWebInfResource(MinimalDigestMechTestCase.class.getPackage(), NAME + "-web.xml", "web.xml");
}
static class ServerSetup extends AbstractMechTestBase.ServerSetup {
@Override
protected boolean useAuthenticationFactory() {
return false;
}
@Override
protected MechanismConfiguration getMechanismConfiguration() {
// As we are not using an authentication factory the mechanisms do not require configuration.
return null;
}
}
}
| 2,950
| 39.986111
| 118
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/http/PasswordMechTestBase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.http;
import static org.apache.http.HttpStatus.SC_FORBIDDEN;
import static org.apache.http.HttpStatus.SC_OK;
import static org.apache.http.HttpStatus.SC_UNAUTHORIZED;
import static org.junit.Assert.assertEquals;
import java.net.URI;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
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.as.test.integration.security.common.servlets.SimpleServlet;
import org.junit.Test;
/**
* Abstract parent for password-based Elytron HTTP mechanisms tests.
*
* @author Jan Kalina
*/
abstract class PasswordMechTestBase extends AbstractMechTestBase {
@Test
public void testSuccess() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1"));
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password1");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
try (CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build()) {
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", SimpleServlet.RESPONSE_BODY, EntityUtils.toString(response.getEntity()));
}
}
}
@Test
public void testInsufficientRole() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role2"));
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password1");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
try (CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build()) {
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_FORBIDDEN, statusCode);
}
}
}
@Test
public void testInvalidPrincipal() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1"));
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1wrong", "password1");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
try (CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build()) {
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
}
}
}
@Test
public void testInvalidCredential() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1"));
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password1wrong");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
try (CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build()) {
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
}
}
}
}
| 5,478
| 44.658333
| 142
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/http/DigestSha256MechTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.http;
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.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.SimpleServlet;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
import org.wildfly.test.security.common.elytron.MechanismConfiguration;
import org.wildfly.test.security.common.elytron.MechanismRealmConfiguration;
/**
* Test of DIGEST-SHA-256 HTTP mechanism.
*
* @author Jan Kalina
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ DigestSha256MechTestCase.ServerSetup.class })
public class DigestSha256MechTestCase extends PasswordMechTestBase {
private static final String NAME = DigestSha256MechTestCase.class.getSimpleName();
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, NAME + ".war")
.addClasses(SimpleServlet.class)
.addAsWebInfResource(Utils.getJBossWebXmlAsset(APP_DOMAIN), "jboss-web.xml")
.addAsWebInfResource(DigestSha256MechTestCase.class.getPackage(), NAME + "-web.xml", "web.xml");
}
static class ServerSetup extends AbstractMechTestBase.ServerSetup {
@Override protected MechanismConfiguration getMechanismConfiguration() {
return MechanismConfiguration.builder()
.withMechanismName("DIGEST-SHA-256")
.addMechanismRealmConfiguration(MechanismRealmConfiguration.builder()
.withRealmName("Digest SHA-256 kingdom")
.build())
.build();
}
}
}
| 2,955
| 42.470588
| 112
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/http/DigestMechTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.http;
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.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.SimpleServlet;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
import org.wildfly.test.security.common.elytron.MechanismConfiguration;
import org.wildfly.test.security.common.elytron.MechanismRealmConfiguration;
/**
* Test of DIGEST HTTP mechanism.
*
* @author Jan Kalina
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ DigestMechTestCase.ServerSetup.class })
public class DigestMechTestCase extends PasswordMechTestBase {
private static final String NAME = DigestMechTestCase.class.getSimpleName();
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, NAME + ".war")
.addClasses(SimpleServlet.class)
.addAsWebInfResource(Utils.getJBossWebXmlAsset(APP_DOMAIN), "jboss-web.xml")
.addAsWebInfResource(DigestMechTestCase.class.getPackage(), NAME + "-web.xml", "web.xml");
}
static class ServerSetup extends AbstractMechTestBase.ServerSetup {
@Override protected MechanismConfiguration getMechanismConfiguration() {
return MechanismConfiguration.builder()
.withMechanismName("DIGEST")
.addMechanismRealmConfiguration(MechanismRealmConfiguration.builder()
.withRealmName("Digest kingdom")
.build())
.build();
}
}
}
| 2,907
| 41.764706
| 106
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/http/AbstractMechTestBase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.http;
import static org.apache.http.HttpStatus.SC_OK;
import static org.apache.http.HttpStatus.SC_UNAUTHORIZED;
import static org.junit.Assert.assertEquals;
import java.net.URI;
import java.net.URL;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.test.api.ArquillianResource;
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.SimpleServlet;
import org.junit.Test;
import org.wildfly.test.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
import org.wildfly.test.security.common.elytron.MechanismConfiguration;
import org.wildfly.test.security.common.elytron.SimpleHttpAuthenticationFactory;
/**
* Abstract parent for Elytron HTTP mechanisms tests.
*
* @author Jan Kalina
*/
abstract class AbstractMechTestBase {
static final String APP_DOMAIN = "MechTestAppDomain";
private static final String DEFAULT_SECURITY_DOMAIN = "ApplicationDomain";
private static final String DEFAULT_MECHANISM_FACTORY = "global";
private static final String HTTP_FACTORY = "MechTestHttpFactory";
@ArquillianResource
protected URL url;
@ArquillianResource
protected ManagementClient mgmtClient;
@Test
public void testUnprotected() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "unprotected"));
HttpClientContext context = HttpClientContext.create();
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
try (CloseableHttpResponse response = httpClient.execute(request, context)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", SimpleServlet.RESPONSE_BODY, EntityUtils.toString(response.getEntity()));
}
}
}
@Test
public void testUnauthorized() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1"));
HttpClientContext context = HttpClientContext.create();
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
try (CloseableHttpResponse response = httpClient.execute(request, context)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
}
}
}
abstract static class ServerSetup extends AbstractElytronSetupTask {
protected abstract MechanismConfiguration getMechanismConfiguration();
protected String getSecurityDomain() {
return DEFAULT_SECURITY_DOMAIN;
}
protected boolean useAuthenticationFactory() {
return true;
}
@Override
protected ConfigurableElement[] getConfigurableElements() {
ConfigurableElement[] elements = useAuthenticationFactory() ? new ConfigurableElement[2] : new ConfigurableElement[1];
if (useAuthenticationFactory()) {
elements[0] = SimpleHttpAuthenticationFactory.builder()
.withName(HTTP_FACTORY)
.withHttpServerMechanismFactory(DEFAULT_MECHANISM_FACTORY)
.withSecurityDomain(getSecurityDomain())
.addMechanismConfiguration(getMechanismConfiguration())
.build();
}
elements[elements.length - 1] = new ConfigurableElement() {
@Override
public String getName() {
return "Configure undertow application-security-domain " + APP_DOMAIN;
}
@Override
public void create(CLIWrapper cli) throws Exception {
String argument = useAuthenticationFactory() ? "http-authentication-factory=" + HTTP_FACTORY : "security-domain=" + getSecurityDomain();
cli.sendLine("/subsystem=undertow/application-security-domain=" + APP_DOMAIN + ":add(" + argument + ")");
}
@Override
public void remove(CLIWrapper cli) throws Exception {
cli.sendLine("/subsystem=undertow/application-security-domain=" + APP_DOMAIN + ":remove");
}
};
return elements;
}
}
}
| 5,975
| 41.382979
| 156
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/http/BasicMechTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.http;
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.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.SimpleServlet;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
import org.wildfly.test.security.common.elytron.MechanismConfiguration;
import org.wildfly.test.security.common.elytron.MechanismRealmConfiguration;
/**
* Test of BASIC HTTP mechanism.
*
* @author Jan Kalina
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ BasicMechTestCase.ServerSetup.class })
public class BasicMechTestCase extends PasswordMechTestBase {
private static final String NAME = BasicMechTestCase.class.getSimpleName();
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, NAME + ".war")
.addClasses(SimpleServlet.class)
.addAsWebInfResource(Utils.getJBossWebXmlAsset(APP_DOMAIN), "jboss-web.xml")
.addAsWebInfResource(BasicMechTestCase.class.getPackage(), NAME + "-web.xml", "web.xml");
}
static class ServerSetup extends AbstractMechTestBase.ServerSetup {
@Override protected MechanismConfiguration getMechanismConfiguration() {
return MechanismConfiguration.builder()
.withMechanismName("BASIC")
.addMechanismRealmConfiguration(MechanismRealmConfiguration.builder()
.withRealmName("Basic kingdom")
.build())
.build();
}
}
}
| 2,900
| 41.661765
| 105
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/http/MinimalFormMechTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.http;
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.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.SimpleServlet;
import org.jboss.as.test.integration.web.sso.LogoutServlet;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
import org.wildfly.test.security.common.elytron.MechanismConfiguration;
/**
* Test of FORM HTTP mechanism using a direct reference to the security domain instead of an authentication factory.
*
* @author Jan Kalina
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ MinimalFormMechTestCase.ServerSetup.class })
public class MinimalFormMechTestCase extends FormMechTestBase {
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, NAME + ".war")
.addClasses(SimpleServlet.class)
.addClasses(LogoutServlet.class)
.addAsWebInfResource(Utils.getJBossWebXmlAsset(APP_DOMAIN), "jboss-web.xml")
.addAsWebResource(new StringAsset(LOGIN_PAGE_CONTENT), "login.html")
.addAsWebResource(new StringAsset(ERROR_PAGE_CONTENT), "error.html")
.addAsWebInfResource(FormMechTestCase.class.getPackage(), NAME + "-web.xml", "web.xml");
}
static class ServerSetup extends AbstractMechTestBase.ServerSetup {
@Override
protected boolean useAuthenticationFactory() {
return false;
}
@Override
protected MechanismConfiguration getMechanismConfiguration() {
// As we are not using an authentication factory the mechanisms do not require configuration.
return null;
}
}
}
| 3,148
| 40.986667
| 116
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/http/FormMechTestBase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.http;
import static org.apache.http.HttpStatus.SC_FORBIDDEN;
import static org.apache.http.HttpStatus.SC_MOVED_TEMPORARILY;
import static org.apache.http.HttpStatus.SC_OK;
import static org.jboss.as.test.integration.security.common.servlets.SimpleServlet.RESPONSE_BODY;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
/**
* Test of FORM HTTP mechanism.
*
* @author Jan Kalina
*/
abstract class FormMechTestBase extends AbstractMechTestBase {
protected static final String NAME = FormMechTestCase.class.getSimpleName();
protected static final String LOGIN_PAGE_CONTENT = "LOGINPAGE";
protected static final String ERROR_PAGE_CONTENT = "ERRORPAGE";
@Test
@Override
public void testUnauthorized() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1"));
HttpClientContext context = HttpClientContext.create();
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
try (CloseableHttpResponse response = httpClient.execute(request, context)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", LOGIN_PAGE_CONTENT, EntityUtils.toString(response.getEntity()));
}
}
}
@Test
public void testLoginPage() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "login.html"));
HttpClientContext context = HttpClientContext.create();
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
try (CloseableHttpResponse response = httpClient.execute(request, context)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", LOGIN_PAGE_CONTENT, EntityUtils.toString(response.getEntity()));
}
}
}
@Test
public void testCorrectWorkflow() throws Exception {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().build()) {
// unauthorized - login form should be shown
HttpGet request1 = new HttpGet(new URI(url.toExternalForm() + "role1"));
try (CloseableHttpResponse response = httpClient.execute(request1)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", LOGIN_PAGE_CONTENT, EntityUtils.toString(response.getEntity()));
}
// logging-in
HttpPost request2 = createLoginRequest( "user1", "password1");
try (CloseableHttpResponse response = httpClient.execute(request2)) {
int statusCode = response.getStatusLine().getStatusCode();
Header[] locations = response.getHeaders("Location");
assertEquals("Unexpected status code in HTTP response.", SC_MOVED_TEMPORARILY, statusCode);
assertEquals("Missing redirect in HTTP response.", 1, locations.length);
assertEquals("Unexpected redirect in HTTP response.", url.toExternalForm() + "role1", locations[0].getValue());
}
// should be logged now
HttpGet request3 = new HttpGet(new URI(url.toExternalForm() + "role1"));
try (CloseableHttpResponse response = httpClient.execute(request3)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", RESPONSE_BODY, EntityUtils.toString(response.getEntity()));
}
// but no role2
HttpGet request4 = new HttpGet(new URI(url.toExternalForm() + "role2"));
try (CloseableHttpResponse response = httpClient.execute(request4)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_FORBIDDEN, statusCode);
assertNotEquals("Unexpected content of HTTP response.", RESPONSE_BODY, EntityUtils.toString(response.getEntity()));
}
// try to log-out
HttpGet request5 = new HttpGet(new URI(url.toExternalForm() + "logout"));
try (CloseableHttpResponse response = httpClient.execute(request5)) {
int statusCode = response.getStatusLine().getStatusCode();
Header[] locations = response.getHeaders("Location");
assertEquals("Unexpected status code in HTTP response.", SC_MOVED_TEMPORARILY, statusCode);
assertEquals("Missing redirect in HTTP response.", 1, locations.length);
assertEquals("Unexpected redirect in HTTP response.", url.toExternalForm() + "index.html", locations[0].getValue());
}
// should be logged-out again
HttpGet request6 = new HttpGet(new URI(url.toExternalForm() + "role1"));
try (CloseableHttpResponse response = httpClient.execute(request6)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", LOGIN_PAGE_CONTENT, EntityUtils.toString(response.getEntity()));
}
}
}
@Test
public void testInvalidPrincipal() throws Exception {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().build()) {
HttpPost request = createLoginRequest("user1wrong", "password1");
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", ERROR_PAGE_CONTENT, EntityUtils.toString(response.getEntity()));
}
}
}
@Test
public void testInvalidCredential() throws Exception {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().build()) {
HttpPost request = createLoginRequest("user1", "password1wrong");
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", ERROR_PAGE_CONTENT, EntityUtils.toString(response.getEntity()));
}
}
}
@Test
public void testEmptyUsername() throws Exception {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().build()) {
HttpPost emptyUsernameRequest = createLoginRequest("", "non-empty-password");
try (CloseableHttpResponse response = httpClient.execute(emptyUsernameRequest)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", ERROR_PAGE_CONTENT,
EntityUtils.toString(response.getEntity()));
}
HttpPost emptyUsernameAndPasswordLoginRequest = createLoginRequest("", "");
try (CloseableHttpResponse response = httpClient.execute(emptyUsernameAndPasswordLoginRequest)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", ERROR_PAGE_CONTENT,
EntityUtils.toString(response.getEntity()));
}
}
}
protected HttpPost createLoginRequest(String username, String password)
throws Exception {
HttpPost request = new HttpPost(new URI(url.toExternalForm() + "j_security_check"));
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("j_username", username));
params.add(new BasicNameValuePair("j_password", password));
request.setEntity(new UrlEncodedFormEntity(params));
return request;
}
}
| 10,622
| 52.115
| 133
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/http/SilentBasicMechTestCase.java
|
/*
* Copyright 2019 Red Hat, Inc.
*
* 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.http;
import static org.apache.http.HttpStatus.SC_OK;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.auth.BasicScheme;
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.as.arquillian.api.ServerSetup;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.SimpleServlet;
import org.jboss.as.test.integration.web.sso.LogoutServlet;
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;
import org.wildfly.test.security.common.elytron.MechanismConfiguration;
/**
* Test of silent BASIC HTTP mechanism.
*
* Basic authentication in silent mode will send a challenge only if the request
* contained authorization header, otherwise it is assumed another method will
* send the challenge. This behaviour will allow to combine basic auth with form
* auth, so human users will use form based auth and programmatic clients can
* use basic authentication to log in.
*
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ SilentBasicMechTestCase.ServerSetup.class})
public class SilentBasicMechTestCase extends FormMechTestBase {
private static final String FORBIDDEN_CONTENT = "Forbidden";
private static final String NAME = SilentBasicMechTestCase.class.getSimpleName();
private static final String LOGIN_PAGE_CONTENT = "LOGINPAGE";
private static final String ERROR_PAGE_CONTENT = "ERRORPAGE";
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, NAME + ".war")
.addClasses(SimpleServlet.class)
.addClasses(LogoutServlet.class)
.addAsWebInfResource(Utils.getJBossWebXmlAsset(APP_DOMAIN), "jboss-web.xml")
.addAsWebResource(new StringAsset(LOGIN_PAGE_CONTENT), "login.html")
.addAsWebResource(new StringAsset(ERROR_PAGE_CONTENT), "error.html")
.addAsWebInfResource(SilentBasicMechTestCase.class.getPackage(), NAME + "-web.xml", "web.xml");
}
static class ServerSetup extends AbstractMechTestBase.ServerSetup {
@Override
protected boolean useAuthenticationFactory() {
return false;
}
@Override protected MechanismConfiguration getMechanismConfiguration() {
return null;
}
}
@Test
public void testBasicWithCredentialSuccess() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1"));
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password1");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build()) {
request.addHeader(new BasicScheme().authenticate(credentials, request, null));
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
assertEquals("Unexpected content of HTTP response.", SimpleServlet.RESPONSE_BODY, EntityUtils.toString(response.getEntity()));
}
}
}
@Test
public void testInsufficientRole() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role2"));
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password1");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
try (CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build()) {
request.addHeader(new BasicScheme().authenticate(credentials, request, null));
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", HttpStatus.SC_FORBIDDEN, statusCode);
assertTrue("Unexpected content of HTTP response.", EntityUtils.toString(response.getEntity()).contains(FORBIDDEN_CONTENT));
}
}
}
@Override
@Test
public void testInvalidPrincipal() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1"));
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1wrong", "password1");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
try (CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build()) {
request.addHeader(new BasicScheme().authenticate(credentials, request, null));
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", HttpStatus.SC_UNAUTHORIZED, statusCode);
assertEquals("Unexpected content of HTTP response.", LOGIN_PAGE_CONTENT, EntityUtils.toString(response.getEntity()));
}
}
}
@Override
@Test
public void testInvalidCredential() throws Exception {
HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1"));
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password1wrong");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
try (CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build()) {
request.addHeader(new BasicScheme().authenticate(credentials, request, null));
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code in HTTP response.", HttpStatus.SC_UNAUTHORIZED, statusCode);
assertEquals("Unexpected content of HTTP response.", LOGIN_PAGE_CONTENT, EntityUtils.toString(response.getEntity()));
}
}
}
}
| 8,104
| 46.676471
| 142
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/http/MinimalBasicMechTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.http;
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.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.SimpleServlet;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
import org.wildfly.test.security.common.elytron.MechanismConfiguration;
/**
* Test of BASIC HTTP mechanism using a direct reference to the security domain instead of an authentication factory.
*
* @author Jan Kalina
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ MinimalBasicMechTestCase.ServerSetup.class })
public class MinimalBasicMechTestCase extends PasswordMechTestBase {
private static final String NAME = MinimalBasicMechTestCase.class.getSimpleName();
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, NAME + ".war")
.addClasses(SimpleServlet.class)
.addAsWebInfResource(Utils.getJBossWebXmlAsset(APP_DOMAIN), "jboss-web.xml")
.addAsWebInfResource(MinimalBasicMechTestCase.class.getPackage(), BasicMechTestCase.class.getSimpleName() + "-web.xml", "web.xml");
}
static class ServerSetup extends AbstractMechTestBase.ServerSetup {
@Override
protected boolean useAuthenticationFactory() {
return false;
}
@Override
protected MechanismConfiguration getMechanismConfiguration() {
// As we are not using an authentication factory the mechanisms do not require configuration.
return null;
}
}
}
| 2,980
| 40.402778
| 147
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/http/FormMechTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.http;
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.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.SimpleServlet;
import org.jboss.as.test.integration.web.sso.LogoutServlet;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
import org.wildfly.test.security.common.elytron.MechanismConfiguration;
/**
* Test of FORM HTTP mechanism.
*
* @author Jan Kalina
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ FormMechTestCase.ServerSetup.class })
public class FormMechTestCase extends FormMechTestBase {
static class ServerSetup extends AbstractMechTestBase.ServerSetup {
@Override protected MechanismConfiguration getMechanismConfiguration() {
return MechanismConfiguration.builder()
.withMechanismName("FORM")
.build();
}
}
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, NAME + ".war")
.addClasses(SimpleServlet.class)
.addClasses(LogoutServlet.class)
.addAsWebInfResource(Utils.getJBossWebXmlAsset(APP_DOMAIN), "jboss-web.xml")
.addAsWebResource(new StringAsset(LOGIN_PAGE_CONTENT), "login.html")
.addAsWebResource(new StringAsset(ERROR_PAGE_CONTENT), "error.html")
.addAsWebInfResource(FormMechTestCase.class.getPackage(), NAME + "-web.xml", "web.xml");
}
}
| 2,844
| 40.838235
| 100
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/securitydomain/SecurityDomainTestCase.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.wildfly.test.integration.elytron.securitydomain;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.codehaus.plexus.util.StringUtils;
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.management.util.CLIWrapper;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.RolePrintingServlet;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import static org.junit.Assert.fail;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.test.integration.elytron.rolemappers.AddPrefixRoleMapperTestCase;
import org.wildfly.test.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
import org.wildfly.test.security.common.elytron.PropertiesRealm;
import org.wildfly.test.security.common.elytron.SimpleSecurityDomain;
import org.wildfly.test.security.common.elytron.UndertowDomainMapper;
/**
* Test case for 'security-domain' Elytron subsystem resource. Testing of most of functionality and attributes of Elytron
* security-domain subsystem resource is covered by another test cases in {@link org.wildfly.test.integration.elytron.*}
* package. This test case covers only scenarios which are not covered by different test cases.
*
* @author olukas
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({SecurityDomainTestCase.SetupTask.class})
public class SecurityDomainTestCase {
private static final String DEFAULT_REALM = "default-realm-test";
private static final String ROLE_MAPPER_PRIORITY = "role-mapper-priority-test";
private static final String PRINCIPAL_TRANSFORMER_ORDER = "principal-transformer-order-test";
private static final String ROLE_MAPPER_FOR_SECURITY_DOMAIN = "rm1";
private static final String ROLE_MAPPER_FOR_REALM = "rm2";
private static final String PRE_REALM_TRANSFORMER_NAME = "suf1";
private static final String POST_REALM_TRANSFORMER_NAME = "suf2";
private static final String REALM_TRANSFORMER_NAME = "suf3";
private static final String USER_IN_SIMPLE_REALM = "userInSimpleRealm";
private static final String PASSWORD_FOR_USER_IN_SIMPLE_REALM = "passwordSimpleRealm";
private static final String USER_IN_ROLE_MAPPER_REALM = "userInRoleMapperRealm";
private static final String PASSWORD_FOR_USER_IN_ROLE_MAPPER_REALM = "passwordRoleMapperRealm";
private static final String USER_BEFORE_TRANSFORMATION = "user";
private static final String TRANSFORMED_USER = "user" + PRE_REALM_TRANSFORMER_NAME + POST_REALM_TRANSFORMER_NAME
+ REALM_TRANSFORMER_NAME;
private static final String PASSWORD_FOR_TRANSFORMED_USER = "passwordForTransformedUser";
private static final String SIMPLE_ROLE = "Role";
private static final String ROLE_MAPPER_PRIORITY_ROLE = ROLE_MAPPER_FOR_SECURITY_DOMAIN + ROLE_MAPPER_FOR_REALM
+ SIMPLE_ROLE;
private static final String ROLE_MAPPER_PRIORITY_WRONG_PRIORITY_ROLE = ROLE_MAPPER_FOR_REALM
+ ROLE_MAPPER_FOR_SECURITY_DOMAIN + SIMPLE_ROLE;
private static final String[] ALL_TESTED_ROLES = {SIMPLE_ROLE, ROLE_MAPPER_PRIORITY_ROLE,
ROLE_MAPPER_PRIORITY_WRONG_PRIORITY_ROLE};
private static final String queryRoles;
static {
final List<NameValuePair> qparams = new ArrayList<>();
for (final String role : ALL_TESTED_ROLES) {
qparams.add(new BasicNameValuePair(RolePrintingServlet.PARAM_ROLE_NAME, role));
}
queryRoles = URLEncodedUtils.format(qparams, StandardCharsets.UTF_8);
}
@Deployment(name = DEFAULT_REALM)
public static WebArchive defaultRealmDeployment() {
return deployment(DEFAULT_REALM);
}
@Deployment(name = ROLE_MAPPER_PRIORITY)
public static WebArchive roleMapperPriorityDeployment() {
return deployment(ROLE_MAPPER_PRIORITY);
}
@Deployment(name = PRINCIPAL_TRANSFORMER_ORDER)
public static WebArchive principalTransformerOrderDeployment() {
return deployment(PRINCIPAL_TRANSFORMER_ORDER);
}
public static WebArchive deployment(String deploymentName) {
final WebArchive war = ShrinkWrap.create(WebArchive.class, deploymentName + ".war");
war.addClasses(RolePrintingServlet.class);
war.addAsWebInfResource(SecurityDomainTestCase.class.getPackage(), "security-domain-web.xml", "web.xml");
war.addAsWebInfResource(Utils.getJBossWebXmlAsset(deploymentName), "jboss-web.xml");
return war;
}
/**
* Test whether default realm is correctly chosen from provided realms in security domain.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEFAULT_REALM)
public void testDefaultRealmIsUsed(@ArquillianResource URL webAppURL) throws Exception {
URL url = prepareRolesPrintingURL(webAppURL);
testAssignedRoles(url, USER_IN_SIMPLE_REALM, PASSWORD_FOR_USER_IN_SIMPLE_REALM, SIMPLE_ROLE);
}
/**
* Test whether non-default realm is not used even if correct user with correct password from that non-default realm try to
* access application secured by given security domain.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(DEFAULT_REALM)
public void testUserFromNonDefaultRealmIsDenied(@ArquillianResource URL webAppURL) throws Exception {
assertAuthenticationFailed(webAppURL, USER_IN_ROLE_MAPPER_REALM, PASSWORD_FOR_USER_IN_ROLE_MAPPER_REALM);
}
/**
* Test whether role-mapper in realm is applied before role-mapper in security-domain.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(ROLE_MAPPER_PRIORITY)
public void testRoleMapperPriorityForRealm(@ArquillianResource URL webAppURL) throws Exception {
URL url = prepareRolesPrintingURL(webAppURL);
testAssignedRoles(url, USER_IN_ROLE_MAPPER_REALM, PASSWORD_FOR_USER_IN_ROLE_MAPPER_REALM, ROLE_MAPPER_PRIORITY_ROLE);
}
/**
* Test whether principal transformers are applied in order: pre-realm-principal-transformer,
* post-realm-principal-transformer, realm.principal-transformer.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(PRINCIPAL_TRANSFORMER_ORDER)
public void testPrincipalTransformerOrder(@ArquillianResource URL webAppURL) throws Exception {
URL url = prepareRolesPrintingURL(webAppURL);
testAssignedRoles(url, USER_BEFORE_TRANSFORMATION, PASSWORD_FOR_TRANSFORMED_USER, SIMPLE_ROLE);
}
private URL prepareRolesPrintingURL(URL webAppURL) throws MalformedURLException {
return new URL(webAppURL.toExternalForm() + RolePrintingServlet.SERVLET_PATH.substring(1) + "?" + queryRoles);
}
private void assertAuthenticationFailed(URL webAppURL, String username, String password) throws Exception {
final URL rolesPrintingURL = prepareRolesPrintingURL(webAppURL);
Utils.makeCallWithBasicAuthn(rolesPrintingURL, username, password, SC_UNAUTHORIZED);
}
private void testAssignedRoles(URL webAppURL, String username, String password, String... assignedRoles) throws Exception {
final URL rolesPrintingURL = prepareRolesPrintingURL(webAppURL);
final String rolesResponse = Utils.makeCallWithBasicAuthn(rolesPrintingURL, username, password, SC_OK);
final List<String> assignedRolesList = Arrays.asList(assignedRoles);
for (String role : ALL_TESTED_ROLES) {
if (assignedRolesList.contains(role)) {
assertInRole(rolesResponse, role);
} else {
assertNotInRole(rolesResponse, role);
}
}
}
private void assertInRole(final String rolePrintResponse, String role) {
if (!StringUtils.contains(rolePrintResponse, "," + role + ",")) {
fail("Missing role '" + role + "' assignment");
}
}
private void assertNotInRole(final String rolePrintResponse, String role) {
if (StringUtils.contains(rolePrintResponse, "," + role + ",")) {
fail("Unexpected role '" + role + "' assignment");
}
}
static class SetupTask extends AbstractElytronSetupTask {
private static final String SIMPLE_REALM = "simpleRealm";
private static final String REALM_FOR_ROLE_MAPPER_PRIORITY = "realmForRoleMapperPriority";
private static final String REALM_FOR_PRINCIPAL_TRANSFORMER_ORDER = "realmForPrincipalTransformerOrder";
@Override
protected ConfigurableElement[] getConfigurableElements() {
List<ConfigurableElement> elements = new ArrayList<>();
elements.add(new AddPrefixRoleMapperTestCase.ServerSetup.AddPrefixRoleMappers(
String.format("%1$s:add(prefix=%1$s)", ROLE_MAPPER_FOR_SECURITY_DOMAIN),
String.format("%1$s:add(prefix=%1$s)", ROLE_MAPPER_FOR_REALM)
));
elements.add(new PrincipalTransformers(PRE_REALM_TRANSFORMER_NAME, POST_REALM_TRANSFORMER_NAME,
REALM_TRANSFORMER_NAME
));
elements.add(PropertiesRealm.builder().withName(SIMPLE_REALM)
.withUser(USER_IN_SIMPLE_REALM, PASSWORD_FOR_USER_IN_SIMPLE_REALM, SIMPLE_ROLE)
.build());
elements.add(PropertiesRealm.builder().withName(REALM_FOR_ROLE_MAPPER_PRIORITY)
.withUser(USER_IN_ROLE_MAPPER_REALM, PASSWORD_FOR_USER_IN_ROLE_MAPPER_REALM, SIMPLE_ROLE)
.build());
elements.add(PropertiesRealm.builder().withName(REALM_FOR_PRINCIPAL_TRANSFORMER_ORDER)
.withUser(TRANSFORMED_USER, PASSWORD_FOR_TRANSFORMED_USER, SIMPLE_ROLE)
.build());
elements.add(SimpleSecurityDomain.builder().withName(DEFAULT_REALM)
.withDefaultRealm(SIMPLE_REALM)
.withPermissionMapper("default-permission-mapper")
.withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder()
.withRealm(REALM_FOR_ROLE_MAPPER_PRIORITY)
.withRoleDecoder("groups-to-roles")
.build(),
SimpleSecurityDomain.SecurityDomainRealm.builder()
.withRealm(SIMPLE_REALM)
.withRoleDecoder("groups-to-roles")
.build())
.build());
elements.add(undertowDomainMapper(DEFAULT_REALM));
elements.add(SimpleSecurityDomain.builder().withName(ROLE_MAPPER_PRIORITY)
.withDefaultRealm(REALM_FOR_ROLE_MAPPER_PRIORITY)
.withPermissionMapper("default-permission-mapper")
.withRoleMapper(ROLE_MAPPER_FOR_SECURITY_DOMAIN)
.withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder()
.withRealm(REALM_FOR_ROLE_MAPPER_PRIORITY)
.withRoleDecoder("groups-to-roles")
.withRoleMapper(ROLE_MAPPER_FOR_REALM)
.build())
.build());
elements.add(undertowDomainMapper(ROLE_MAPPER_PRIORITY));
elements.add(SimpleSecurityDomain.builder().withName(PRINCIPAL_TRANSFORMER_ORDER)
.withDefaultRealm(REALM_FOR_PRINCIPAL_TRANSFORMER_ORDER)
.withPermissionMapper("default-permission-mapper")
.withPreRealmPrincipalTransformer(PRE_REALM_TRANSFORMER_NAME)
.withPostRealmPrincipalTransformer(POST_REALM_TRANSFORMER_NAME)
.withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder()
.withRealm(REALM_FOR_PRINCIPAL_TRANSFORMER_ORDER)
.withRoleDecoder("groups-to-roles")
.withPrincipalTransformer(REALM_TRANSFORMER_NAME)
.build())
.build());
elements.add(undertowDomainMapper(PRINCIPAL_TRANSFORMER_ORDER));
return elements.toArray(new ConfigurableElement[elements.size()]);
}
private ConfigurableElement undertowDomainMapper(String name) {
return UndertowDomainMapper.builder()
.withName(name)
.withApplicationDomains(name)
.build();
}
public static class PrincipalTransformers implements ConfigurableElement {
private final String[] suffixsToAdd;
public PrincipalTransformers(String... suffixsToAdd) {
this.suffixsToAdd = suffixsToAdd;
}
@Override
public void create(CLIWrapper cli) throws Exception {
for (String sfx : suffixsToAdd) {
cli.sendLine("/subsystem=elytron/regex-principal-transformer=" + sfx + ":add(pattern=$,replacement=" + sfx + ")");
}
}
@Override
public void remove(CLIWrapper cli) throws Exception {
for (String sfx : suffixsToAdd) {
cli.sendLine("/subsystem=elytron/regex-principal-transformer=" + sfx + ":remove()");
}
}
@Override
public String getName() {
return "regex-principal-transformer";
}
}
}
}
| 15,316
| 46.129231
| 134
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/batch/LongRunningBatchlet.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
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.batch;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import jakarta.batch.api.Batchlet;
import jakarta.batch.runtime.context.JobContext;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import org.jboss.as.test.shared.TimeoutUtil;
/**
* @author Jan Martiska
*/
@Named
public class LongRunningBatchlet implements Batchlet {
private final CompletableFuture<Void> SHOULD_STOP = new CompletableFuture<>();
@Inject
JobContext ctx;
@Override
public String process() throws Exception {
SHOULD_STOP.get(TimeoutUtil.adjust(10), TimeUnit.SECONDS);
return null;
}
@Override
public void stop() throws Exception {
SHOULD_STOP.complete(null);
}
}
| 1,820
| 31.517857
| 82
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/batch/FailingBatchlet.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
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.batch;
import jakarta.batch.api.BatchProperty;
import jakarta.batch.api.Batchlet;
import jakarta.inject.Inject;
import jakarta.inject.Named;
/**
* @author Jan Martiska
*/
@Named
public class FailingBatchlet implements Batchlet {
@Inject
@BatchProperty(name = "should.fail")
private Boolean shouldFail;
@Override
public String process() throws Exception {
if(shouldFail)
throw new Exception("failing the job on purpose");
return "OK";
}
@Override
public void stop() throws Exception {
}
}
| 1,629
| 30.346154
| 70
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/batch/SecurityDomainSettingEJB.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
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.batch;
import jakarta.ejb.LocalBean;
import jakarta.ejb.Stateless;
import org.jboss.ejb3.annotation.SecurityDomain;
/**
* This is here as just a hack to be able to set the security domain of a deployment.
* See https://issues.jboss.org/browse/JBEAP-8702 discussion for more context.
* @author Jan Martiska
*/
@Stateless
@SecurityDomain("BatchDomain")
@LocalBean
public class SecurityDomainSettingEJB {
}
| 1,480
| 36.025
| 85
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/batch/IdentityBatchlet.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
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.batch;
import jakarta.batch.api.Batchlet;
import jakarta.inject.Named;
import org.jboss.logging.Logger;
import org.wildfly.security.auth.server.SecurityDomain;
/**
* @author Jan Martiska
*/
@Named
public class IdentityBatchlet implements Batchlet {
private Logger logger = Logger.getLogger(IdentityBatchlet.class);
@Override
public String process() throws Exception {
final String name = SecurityDomain.getCurrent().getCurrentSecurityIdentity().getPrincipal().getName();
logger.info("Batchlet running as username: " + name);
BatchSubsystemSecurityTestCase.identityWithinJob.complete(name);
return "OK";
}
@Override
public void stop() throws Exception {
}
}
| 1,795
| 33.538462
| 110
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/batch/BatchSubsystemSecurityTestCase.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
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.batch;
import static org.jboss.as.controller.client.helpers.ClientConstants.ADDRESS;
import static org.jboss.as.controller.client.helpers.ClientConstants.OP;
import static org.jboss.as.controller.client.helpers.ClientConstants.WRITE_ATTRIBUTE_OPERATION;
import java.security.AllPermission;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import jakarta.batch.operations.JobOperator;
import jakarta.batch.operations.JobSecurityException;
import jakarta.batch.runtime.BatchRuntime;
import jakarta.batch.runtime.BatchStatus;
import org.jboss.arquillian.container.test.api.Deployment;
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.PathAddress;
import org.jboss.as.test.shared.CdiUtils;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.as.test.shared.SnapshotRestoreSetupTask;
import org.jboss.as.test.shared.TimeoutUtil;
import org.jboss.as.test.shared.integration.ejb.security.PermissionUtils;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.extension.batch.jberet.deployment.BatchPermission;
import org.wildfly.security.auth.permission.LoginPermission;
import org.wildfly.security.auth.server.RealmUnavailableException;
import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.security.auth.server.SecurityIdentity;
import org.wildfly.security.evidence.PasswordGuessEvidence;
import org.wildfly.test.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
import org.wildfly.test.security.common.elytron.EJBApplicationSecurityDomainMapping;
import org.wildfly.test.security.common.elytron.PermissionRef;
import org.wildfly.test.security.common.elytron.PropertyFileBasedDomain;
import org.wildfly.test.security.common.elytron.SimplePermissionMapper;
/**
* This is for testing the BatchPermission from batch-jberet subsystem.
* It also checks that when running a Batch job as a particular user, the security identity can be retrieved
* within the job's code.
*
* The security setup is like this:
* user1/password1 -> can do everything
* user2/password2 -> can stop jobs only
* user3/password3 -> can read jobs only
*
* @author Jan Martiska
*/
@ServerSetup({BatchSubsystemSecurityTestCase.CreateBatchSecurityDomainSetupTask.class,
BatchSubsystemSecurityTestCase.ActivateBatchSecurityDomainSetupTask.class})
@RunWith(Arquillian.class)
public class BatchSubsystemSecurityTestCase {
static final String BATCH_SECURITY_DOMAIN_NAME = "BatchDomain";
@Deployment
public static Archive<?> createDeployment() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "batch-test.jar");
jar.addClasses(AbstractElytronSetupTask.class,
SecurityDomainSettingEJB.class,
TimeoutUtil.class,
IdentityBatchlet.class,
FailingBatchlet.class,
LongRunningBatchlet.class);
jar.addAsManifestResource(BatchSubsystemSecurityTestCase.class.getPackage(),
"assert-identity.xml",
"batch-jobs/assert-identity.xml");
jar.addAsManifestResource(BatchSubsystemSecurityTestCase.class.getPackage(),
"failing-batchlet.xml",
"batch-jobs/failing-batchlet.xml");
jar.addAsManifestResource(BatchSubsystemSecurityTestCase.class.getPackage(),
"long-running-batchlet.xml",
"batch-jobs/long-running-batchlet.xml");
jar.addAsManifestResource(CdiUtils.createBeansXml(), "beans.xml");
jar.addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(new AllPermission()), "permissions.xml");
return jar;
}
// this is the identityWithinJob using which the batch job was invoked
// the job itself completes this future when it runs
static volatile CompletableFuture<String> identityWithinJob;
private JobOperator operator;
@Before
public void before() {
operator = BatchRuntime.getJobOperator();
}
/**
* Try running a job as a user who has the permission to run jobs. It should succeed.
* The job should also be able to retrieve the name of the user who ran it.
*/
@Test
public void testStart_Allowed() throws Exception {
identityWithinJob = new CompletableFuture<>();
final SecurityIdentity user1 = getSecurityIdentity("user1", "password1");
user1.runAs((Callable<Long>)() -> operator.start("assert-identity", new Properties()));
final String actualUsername = identityWithinJob.get(TimeoutUtil.adjust(20), TimeUnit.SECONDS);
Assert.assertEquals("user1", actualUsername);
}
/**
* Try running a job as a user who doesn't have the permission to run jobs. It should not succeed.
*/
@Test
public void testStart_NotAllowed() throws Exception {
final SecurityIdentity user2 = getSecurityIdentity("user2", "password2");
try {
user2.runAs((Callable<Long>)() -> operator.start("assert-identity", new Properties()));
Assert.fail("user2 shouldn't be allowed to start batch jobs");
} catch(JobSecurityException e) {
// OK
}
}
/**
* Test reading execution metadata by a user who has the permission to do it.
* User1 runs a job and then user2 tries to read its metadata.
*/
@Test
public void testRead_Allowed() throws Exception {
final Properties jobParams = new Properties();
jobParams.put("prop1", "val1");
final SecurityIdentity user1 = getSecurityIdentity("user1", "password1");
final SecurityIdentity user3 = getSecurityIdentity("user3", "password3");
final Long executionId = user1
.runAs((Callable<Long>)() -> operator.start("assert-identity", jobParams));
final Properties retrievedParams = user3
.runAs((Callable<Properties>)() -> operator.getJobExecution(executionId).getJobParameters());
Assert.assertEquals(jobParams, retrievedParams);
}
/**
* Test reading execution metadata by a user who doesn't have the permission to do it.
* User1 runs a job and then user2 tries to read its metadata.
*/
@Test
public void testRead_NotAllowed() throws Exception {
final SecurityIdentity user1 = getSecurityIdentity("user1", "password1");
final SecurityIdentity user2 = getSecurityIdentity("user2", "password2");
final Long executionId = user1
.runAs((Callable<Long>)() -> operator.start("assert-identity", new Properties()));
try {
user2.runAs((Callable<Properties>)() -> operator.getJobExecution(executionId).getJobParameters());
Assert.fail("user2 shouldn't be allowed to read batch job metadata");
} catch(JobSecurityException e) {
// OK
}
}
/**
* Test restarting failed jobs by a user who has the permission to do it.
*/
@Test
public void testRestart_Allowed() throws Exception {
final SecurityIdentity user1 = getSecurityIdentity("user1", "password1");
Properties params = new Properties();
params.put("should.fail", "true");
final Long executionId = user1
.runAs((Callable<Long>)() -> operator.start("failing-batchlet", params));
waitForJobEnd(executionId, 10);
Assert.assertEquals(BatchStatus.FAILED, operator.getJobExecution(executionId).getBatchStatus());
params.put("should.fail", "false");
final Long executionIdAfterRestart = user1
.runAs((Callable<Long>)() -> operator.restart(executionId, params));
waitForJobEnd(executionIdAfterRestart, 10);
Assert.assertEquals(BatchStatus.COMPLETED, operator.getJobExecution(executionIdAfterRestart).getBatchStatus());
}
/**
* Test restarting failed jobs by a user who doesn't have the permission to do it.
*/
@Test
public void testRestart_NotAllowed() throws Exception {
final SecurityIdentity user1 = getSecurityIdentity("user1", "password1");
final SecurityIdentity user2 = getSecurityIdentity("user2", "password2");
Properties params = new Properties();
params.put("should.fail", "true");
final Long executionId = user1
.runAs((Callable<Long>)() -> operator.start("failing-batchlet", params));
waitForJobEnd(executionId, 10);
Assert.assertEquals(BatchStatus.FAILED, operator.getJobExecution(executionId).getBatchStatus());
try {
user2.runAs((Callable<Long>)() -> operator.restart(executionId, params));
Assert.fail("user2 shouldn't be allowed to restart batch jobs");
} catch(JobSecurityException e) {
// OK
}
}
/**
* Abandoning an execution by a user who has the permission to do it.
*/
@Test
public void testAbandon_Allowed() throws Exception {
final SecurityIdentity user1 = getSecurityIdentity("user1", "password1");
final Long id = user1.runAs((Callable<Long>)() -> operator.start("assert-identity", new Properties()));
waitForJobEnd(id, 10);
user1.runAs(() -> operator.abandon(id));
Assert.assertEquals(operator.getJobExecution(id).getBatchStatus(), BatchStatus.ABANDONED);
}
/**
* Abandoning an execution by a user who doesn't have the permission to do it.
*/
@Test
public void testAbandon_NotAllowed() throws Exception {
final SecurityIdentity user1 = getSecurityIdentity("user1", "password1");
final SecurityIdentity user2 = getSecurityIdentity("user2", "password2");
final Long id = user1.runAs((Callable<Long>)() -> operator.start("assert-identity", new Properties()));
waitForJobEnd(id, 10);
try {
user2.runAs(() -> operator.abandon(id));
Assert.fail("user2 should not be allowed to abandon job executions");
} catch(JobSecurityException e) {
// OK
}
Assert.assertEquals(operator.getJobExecution(id).getBatchStatus(), BatchStatus.COMPLETED);
}
/**
* Stopping an execution by a user who doesn't have the permission to do it.
*/
@Test
public void testStop_NotAllowed() throws Exception {
final SecurityIdentity user1 = getSecurityIdentity("user1", "password1");
final SecurityIdentity user3 = getSecurityIdentity("user3", "password3");
final Long id = user1.runAs((Callable<Long>)() -> operator.start("long-running-batchlet", null));
TimeUnit.SECONDS.sleep(1);
try {
user3.runAs(() -> operator.stop(id));
Assert.fail("user2 should not be allowed to stop job executions");
} catch(JobSecurityException e) {
// OK
}
Assert.assertNotEquals(BatchStatus.STOPPED, operator.getJobExecution(id).getBatchStatus());
}
/**
* Stopping an execution by a user who has the permission to do it.
*/
@Test
public void testStop_Allowed() throws Exception {
final SecurityIdentity user1 = getSecurityIdentity("user1", "password1");
final Long id = user1.runAs((Callable<Long>)() -> operator.start("long-running-batchlet", null));
TimeUnit.SECONDS.sleep(1);
user1.runAs(() -> operator.stop(id));
waitForJobEnd(id, 10);
Assert.assertEquals(BatchStatus.STOPPED, operator.getJobExecution(id).getBatchStatus());
}
private void waitForJobEnd(Long id, int timeoutSeconds) throws TimeoutException {
Long start = System.currentTimeMillis();
final JobOperator operator = BatchRuntime.getJobOperator();
while(System.currentTimeMillis() - start < (TimeoutUtil.adjust(timeoutSeconds) * 1000)) {
if(operator.getJobExecution(id).getEndTime() != null)
return;
}
throw new TimeoutException();
}
private static SecurityIdentity getSecurityIdentity(String username, String password)
throws RealmUnavailableException {
return SecurityDomain.getCurrent().authenticate(username, new PasswordGuessEvidence(password.toCharArray()));
}
static class CreateBatchSecurityDomainSetupTask extends AbstractElytronSetupTask {
@Override
protected ConfigurableElement[] getConfigurableElements() {
return new ConfigurableElement[] {
SimplePermissionMapper.builder().withName("batch-permission-mapper")
.permissionMappings(
SimplePermissionMapper.PermissionMapping.builder()
.withPrincipals("user1", "anonymous")
.withPermissions(
PermissionRef.builder()
.targetName("*")
.className(BatchPermission.class.getName())
.module("org.wildfly.extension.batch.jberet")
.build(),
PermissionRef.builder()
.className(LoginPermission.class.getName())
.build())
.build(),
SimplePermissionMapper.PermissionMapping.builder()
.withPrincipals("user2")
.withPermissions(
PermissionRef.builder()
.targetName("stop")
.className(BatchPermission.class.getName())
.module("org.wildfly.extension.batch.jberet")
.build(),
PermissionRef.builder()
.className(LoginPermission.class.getName())
.build())
.build(),
SimplePermissionMapper.PermissionMapping.builder()
.withPrincipals("user3")
.withPermissions(
PermissionRef.builder()
.targetName("read")
.className(BatchPermission.class.getName())
.module("org.wildfly.extension.batch.jberet")
.build(),
PermissionRef.builder()
.className(LoginPermission.class.getName())
.build())
.build()
).build(),
PropertyFileBasedDomain.builder().withName(BATCH_SECURITY_DOMAIN_NAME)
.permissionMapper("batch-permission-mapper")
.withUser("user1", "password1")
.withUser("user2", "password2")
.withUser("user3", "password3")
.build(),
new EJBApplicationSecurityDomainMapping(BATCH_SECURITY_DOMAIN_NAME, BATCH_SECURITY_DOMAIN_NAME)
};
}
}
static class ActivateBatchSecurityDomainSetupTask extends SnapshotRestoreSetupTask {
final ModelNode BATCH_SUBSYSTEM_ADDRESS = PathAddress.pathAddress("subsystem", "batch-jberet")
.toModelNode();
@Override
public void doSetup(ManagementClient managementClient, String s) throws Exception {
final ModelNode setOp = new ModelNode();
setOp.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
setOp.get(ADDRESS).set(BATCH_SUBSYSTEM_ADDRESS);
setOp.get("name").set("security-domain");
setOp.get("value").set(BATCH_SECURITY_DOMAIN_NAME);
final ModelNode result = managementClient.getControllerClient().execute(setOp);
Assert.assertTrue(result.get("outcome").asString().equals("success"));
ServerReload.executeReloadAndWaitForCompletion(managementClient);
}
}
}
| 18,450
| 47.427822
| 119
|
java
|
null |
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/principaldecoders/ConstantPrincipalDecoderTestCase.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
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.elytron.principaldecoders;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
import static org.junit.Assert.assertEquals;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
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.common.SecurityTestConstants;
import org.jboss.as.test.integration.security.common.Utils;
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;
import org.wildfly.test.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
import org.wildfly.test.security.common.elytron.ConstantPrincipalDecoder;
import org.wildfly.test.security.common.elytron.ConstantPrincipalTransformer;
import org.wildfly.test.security.common.elytron.PropertiesRealm;
import org.wildfly.test.security.common.elytron.SimpleSecurityDomain;
import org.wildfly.test.security.common.elytron.SimpleSecurityDomain.SecurityDomainRealm;
import org.wildfly.test.security.common.elytron.UndertowDomainMapper;
import org.wildfly.test.security.servlets.SecuredPrincipalPrintingServlet;
/**
* Test for "constant-principal-decoder" Elytron resource. It tests if it's correctly used for authentication and remains valid
* as authenticated principal. It also checks for handling special characters and chaining with a principal transformer.
*
* @author Josef Cacek
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup({ ConstantPrincipalDecoderTestCase.ServerSetup.class })
public class ConstantPrincipalDecoderTestCase {
private static final String STR_SYMBOLS = "@!#?$%^&*()%+-{}";
private static final String STR_CHINESE = "用戶名";
private static final String STR_ARABIC = "اسمالمستخدم";
private static final String STR_EURO_LOWER = "žščřžďťňäáéěëíýóůúü";
private static final String STR_EURO_UPPER = "ŽŠČŘŽĎŤŇÄÁÉĚËÍÝÓŮÚÜ";
private static final String NAME = ConstantPrincipalDecoderTestCase.class.getSimpleName();
private static final String CONST_ADMIN = "admin";
private static final String CONST_WHITESPACE = "two words";
private static final String CONST_I18N = STR_SYMBOLS + STR_CHINESE + STR_ARABIC + STR_EURO_LOWER + STR_EURO_UPPER;
private static final String PD_NAME_ADMIN = CONST_ADMIN + "PD";
private static final String PD_NAME_I18N = "i18n";
private static final String PD_NAME_WHITESPACE = "whitespace";
private static final String SD_NAME_NO_PD = "no-principal-decoder";
private static final String SD_NAME_PD_AND_PT = "decoder-and-transformer";
@Deployment(testable = false, name = PD_NAME_ADMIN)
public static WebArchive deployment1() {
return createWar(PD_NAME_ADMIN);
}
@Deployment(testable = false, name = PD_NAME_I18N)
public static WebArchive deployment2() {
return createWar(PD_NAME_I18N);
}
@Deployment(testable = false, name = PD_NAME_WHITESPACE)
public static WebArchive deployment3() {
return createWar(PD_NAME_WHITESPACE);
}
@Deployment(testable = false, name = SD_NAME_NO_PD)
public static WebArchive deployment5() {
return createWar(SD_NAME_NO_PD);
}
@Deployment(testable = false, name = SD_NAME_PD_AND_PT)
public static WebArchive deployment6() {
return createWar(SD_NAME_PD_AND_PT);
}
/**
* Tests security domain which doesn't contain any principal-decoder.
*/
@Test
@OperateOnDeployment(SD_NAME_NO_PD)
public void testNoPrincipalDecoder(@ArquillianResource URL url) throws Exception {
assertEquals("Response body is not correct.", CONST_ADMIN,
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_ADMIN, CONST_ADMIN, SC_OK));
assertEquals("Response body is not correct.", CONST_WHITESPACE,
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_WHITESPACE, CONST_WHITESPACE, SC_OK));
}
/**
* I18N test for security domain which doesn't contain any principal-decoder.
*/
@Test
@OperateOnDeployment(SD_NAME_NO_PD)
public void testNoPrincipalDecoderI18n(@ArquillianResource URL url) throws Exception {
assertEquals("Response body is not correct.", CONST_I18N,
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_I18N, CONST_I18N, SC_OK));
}
/**
* Tests simple "admin" constant used in the constant-principal-decoder.
*/
@Test
@OperateOnDeployment(PD_NAME_ADMIN)
public void testAdminPrincipalDecoder(@ArquillianResource URL url) throws Exception {
assertEquals("Response body is not correct.", CONST_ADMIN,
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_ADMIN, CONST_ADMIN, SC_OK));
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_WHITESPACE, CONST_WHITESPACE, SC_UNAUTHORIZED);
assertEquals("Response body is not correct.", CONST_ADMIN,
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_WHITESPACE, CONST_ADMIN, SC_OK));
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_I18N, CONST_I18N, SC_UNAUTHORIZED);
assertEquals("Response body is not correct.", CONST_ADMIN,
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_I18N, CONST_ADMIN, SC_OK));
}
/**
* Tests constant with a whitespace used in the constant-principal-decoder.
*/
@Test
@OperateOnDeployment(PD_NAME_WHITESPACE)
public void testWhitespacePrincipalDecoder(@ArquillianResource URL url) throws Exception {
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_ADMIN, CONST_ADMIN, SC_UNAUTHORIZED);
assertEquals("Response body is not correct.", CONST_WHITESPACE,
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_ADMIN, CONST_WHITESPACE, SC_OK));
assertEquals("Response body is not correct.", CONST_WHITESPACE,
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_WHITESPACE, CONST_WHITESPACE, SC_OK));
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_I18N, CONST_I18N, SC_UNAUTHORIZED);
assertEquals("Response body is not correct.", CONST_WHITESPACE,
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_I18N, CONST_WHITESPACE, SC_OK));
}
/**
* Tests i18n constant used in the constant-principal-decoder.
*/
@Test
@OperateOnDeployment(PD_NAME_I18N)
public void testI18NPrincipalDecoder(@ArquillianResource URL url) throws Exception {
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_ADMIN, CONST_ADMIN, SC_UNAUTHORIZED);
assertEquals("Response body is not correct.", CONST_I18N,
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_ADMIN, CONST_I18N, SC_OK));
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_WHITESPACE, CONST_WHITESPACE, SC_UNAUTHORIZED);
assertEquals("Response body is not correct.", CONST_I18N,
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_WHITESPACE, CONST_I18N, SC_OK));
assertEquals("Response body is not correct.", CONST_I18N,
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_I18N, CONST_I18N, SC_OK));
}
/**
* Tests principal-decoder chained with principal-transformer in a security domain.
*/
@Test
@OperateOnDeployment(SD_NAME_PD_AND_PT)
public void testPrincipalDecoderAndTransformer(@ArquillianResource URL url) throws Exception {
assertEquals("Response body is not correct.", CONST_WHITESPACE,
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_ADMIN, CONST_ADMIN, SC_OK));
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_WHITESPACE, CONST_WHITESPACE, SC_UNAUTHORIZED);
assertEquals("Response body is not correct.", CONST_WHITESPACE,
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_WHITESPACE, CONST_ADMIN, SC_OK));
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_I18N, CONST_I18N, SC_UNAUTHORIZED);
assertEquals("Response body is not correct.", CONST_WHITESPACE,
Utils.makeCallWithBasicAuthn(principalServlet(url), CONST_I18N, CONST_ADMIN, SC_OK));
}
/**
* Converts webapp URL to URL containing the included servlet path.
*/
private URL principalServlet(URL url) throws MalformedURLException {
return new URL(url.toExternalForm() + SecuredPrincipalPrintingServlet.SERVLET_PATH.substring(1));
}
/**
* Creates web application with given name security domain name reference. The name is used as the archive name too.
*/
private static WebArchive createWar(final String sd) {
return ShrinkWrap.create(WebArchive.class, sd + ".war").addClasses(SecuredPrincipalPrintingServlet.class)
.addAsWebInfResource(Utils.getJBossWebXmlAsset(sd), "jboss-web.xml")
.addAsWebInfResource(new StringAsset(SecurityTestConstants.WEB_XML_BASIC_AUTHN), "web.xml");
}
/**
* Setup task which configures Elytron security domains for this test.
*/
public static class ServerSetup extends AbstractElytronSetupTask {
private static final String DEFAULT_PERMISSION_MAPPER = "default-permission-mapper";
private static final SecurityDomainRealm SD_REALM_REF = SecurityDomainRealm.builder().withRoleDecoder("groups-to-roles")
.withRealm(NAME).build();
@Override
protected ConfigurableElement[] getConfigurableElements() {
List<ConfigurableElement> elements = new ArrayList<>();
elements.add(PropertiesRealm.builder().withName(NAME)
.withUser(CONST_ADMIN, CONST_ADMIN, SecuredPrincipalPrintingServlet.ALLOWED_ROLE)
.withUser(CONST_I18N, CONST_I18N, SecuredPrincipalPrintingServlet.ALLOWED_ROLE)
.withUser(CONST_WHITESPACE, CONST_WHITESPACE, SecuredPrincipalPrintingServlet.ALLOWED_ROLE).build());
addSecurityDomainWithPermissionMapper(elements, PD_NAME_ADMIN, CONST_ADMIN);
addSecurityDomainWithPermissionMapper(elements, PD_NAME_WHITESPACE, CONST_WHITESPACE);
addSecurityDomainWithPermissionMapper(elements, PD_NAME_I18N, CONST_I18N);
elements.add(SimpleSecurityDomain.builder().withName(SD_NAME_NO_PD).withDefaultRealm(NAME).withRealms(SD_REALM_REF)
.withPermissionMapper(DEFAULT_PERMISSION_MAPPER).build());
elements.add(UndertowDomainMapper.builder().withName(SD_NAME_NO_PD).withApplicationDomains(SD_NAME_NO_PD).build());
elements.add(ConstantPrincipalTransformer.builder().withName(CONST_ADMIN).withConstant(CONST_ADMIN).build());
elements.add(SimpleSecurityDomain.builder().withName(SD_NAME_PD_AND_PT).withDefaultRealm(NAME)
.withRealms(SD_REALM_REF).withPrincipalDecoder(PD_NAME_WHITESPACE)
.withPostRealmPrincipalTransformer(CONST_ADMIN).withPermissionMapper(DEFAULT_PERMISSION_MAPPER).build());
elements.add(UndertowDomainMapper.builder().withName(SD_NAME_PD_AND_PT).withApplicationDomains(SD_NAME_PD_AND_PT)
.build());
return elements.toArray(new ConfigurableElement[elements.size()]);
}
private void addSecurityDomainWithPermissionMapper(List<ConfigurableElement> elements, String pdName,
String pdConstant) {
elements.add(ConstantPrincipalDecoder.builder().withName(pdName).withConstant(pdConstant).build());
elements.add(SimpleSecurityDomain.builder().withName(pdName).withPrincipalDecoder(pdName).withDefaultRealm(NAME)
.withRealms(SD_REALM_REF).withPermissionMapper(DEFAULT_PERMISSION_MAPPER).build());
elements.add(UndertowDomainMapper.builder().withName(pdName).withApplicationDomains(pdName).build());
}
}
}
| 13,528
| 52.900398
| 128
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/DMRUtil.java
|
package org.jboss.as.test.clustering;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.*;
import org.jboss.logging.Logger;
import org.junit.Assert;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.test.integration.management.ManagementOperations;
import org.jboss.dmr.ModelNode;
/**
* @author Ondrej Chaloupka
*/
public class DMRUtil {
private static final Logger log = Logger.getLogger(DMRUtil.class);
private static final String MAX_SIZE_ATTRIBUTE = "max-size";
/**
* Hidden constructor.
*/
private DMRUtil() {
}
/**
* Returning modelnode address for DRM to be able to set cache attributes (client drm call).
*/
private static ModelNode getEJB3PassivationStoreAddress() {
ModelNode address = new ModelNode();
address.add(SUBSYSTEM, "ejb3");
address.add("passivation-store", "infinispan");
address.protect();
return address;
}
/**
* Setting max size cache attribute (client drm call).
*/
public static void setMaxSize(ModelControllerClient client, int maxSize) throws Exception {
ModelNode address = getEJB3PassivationStoreAddress();
ModelNode operation = new ModelNode();
operation.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
operation.get(OP_ADDR).set(address);
operation.get("name").set(MAX_SIZE_ATTRIBUTE);
operation.get("value").set(maxSize);
// ModelNode result = client.execute(operation);
ModelNode result = ManagementOperations.executeOperationRaw(client, operation);
Assert.assertEquals("Setting of max-size attribute was not successful", SUCCESS, result.get(OUTCOME).asString());
}
/**
* Unsetting specific attribute (client drm call).
*/
private static void unsetPassivationAttributes(ModelControllerClient client, String attrName) throws Exception {
ModelNode address = getEJB3PassivationStoreAddress();
ModelNode operation = new ModelNode();
operation.get(OP).set(UNDEFINE_ATTRIBUTE_OPERATION);
operation.get(OP_ADDR).set(address);
operation.get("name").set(attrName);
ModelNode result = client.execute(operation);
Assert.assertEquals("Unset of attribute " + attrName + " on server was not successful", SUCCESS, result.get(OUTCOME).asString());
log.trace("unset modelnode operation " + UNDEFINE_ATTRIBUTE_OPERATION + " on " + attrName + ": " + result);
}
public static void unsetMaxSizeAttribute(ModelControllerClient client) throws Exception {
unsetPassivationAttributes(client, MAX_SIZE_ATTRIBUTE);
}
}
| 2,677
| 36.71831
| 137
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/NodeInfoServlet.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.clustering;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Servlet returning the serving node name.
*
* @author Ondrej Chaloupka
*/
@WebServlet(urlPatterns = { NodeInfoServlet.SERVLET_PATH })
public class NodeInfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String SERVLET_NAME = "nodename";
public static final String SERVLET_PATH = "/" + SERVLET_NAME;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.getWriter().write(NodeNameGetter.getNodeName());
}
}
| 1,828
| 37.914894
| 95
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/TopologyChangeListener.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, 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;
/**
* @author Paul Ferraro
*/
public interface TopologyChangeListener {
long DEFAULT_TIMEOUT = 15000;
/**
* Waits until the specified topology is established on the specified cache.
* @param containerName the cache container name
* @param cacheName the cache name
* @param nodes the anticipated topology
* @throws InterruptedException if topology did not stabilize within a reasonable amount of time - or the process was interrupted.
*/
void establishTopology(String containerName, String cacheName, long timeout, String... nodes) throws InterruptedException;
}
| 1,670
| 40.775
| 134
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/InfinispanServerUtil.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 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.jboss.as.test.clustering;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.INFINISPAN_SERVER_HOME;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.INFINISPAN_SERVER_PROFILE;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.INFINISPAN_SERVER_PROFILE_DEFAULT;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.util.Objects;
import org.infinispan.server.test.core.ServerRunMode;
import org.infinispan.server.test.core.TestSystemPropertyNames;
import org.infinispan.server.test.junit4.InfinispanServerRule;
import org.infinispan.server.test.junit4.InfinispanServerRuleBuilder;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.junit.rules.TestRule;
/**
* @author Radoslav Husar
*/
public class InfinispanServerUtil {
public static final InfinispanServerRule INFINISPAN_SERVER_RULE;
static {
String profile = (INFINISPAN_SERVER_PROFILE == null || INFINISPAN_SERVER_PROFILE.isEmpty()) ? INFINISPAN_SERVER_PROFILE_DEFAULT : INFINISPAN_SERVER_PROFILE;
// Workaround for "ISPN-13107 ServerRunMode.FORKED yields InvalidPathException with relative server config paths on Windows platform" by using absolute file path which won't get mangled.
String absoluteConfigurationFile = null;
try {
absoluteConfigurationFile = Paths.get(Objects.requireNonNull(AbstractClusteringTestCase.class.getClassLoader().getResource(profile)).toURI()).toFile().toString();
} catch (URISyntaxException ignore) {
}
INFINISPAN_SERVER_RULE = InfinispanServerRuleBuilder
.config(absoluteConfigurationFile)
.property(TestSystemPropertyNames.INFINISPAN_TEST_SERVER_DIR, INFINISPAN_SERVER_HOME)
.property("infinispan.client.rest.auth_username", "testsuite-driver-user")
.property("infinispan.client.rest.auth_password", "testsuite-driver-password")
.numServers(1)
.runMode(ServerRunMode.FORKED)
.build();
}
public static TestRule infinispanServerTestRule() {
return INFINISPAN_SERVER_RULE;
}
}
| 3,256
| 44.873239
| 194
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/ClusterHttpClientUtil.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.clustering;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.GRACE_TIME_TO_REPLICATE;
import static org.junit.Assert.assertEquals;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.HttpClients;
/**
* Helper class to start and stop container including a deployment.
*
* @author Radoslav Husar
*/
public final class ClusterHttpClientUtil {
public static void establishTopology(URL baseURL, String container, String cache, String... nodes) throws URISyntaxException, IOException {
establishTopology(baseURL, container, cache, TopologyChangeListener.DEFAULT_TIMEOUT, nodes);
}
public static void establishTopology(URL baseURL, String container, String cache, long timeout, String... nodes) throws URISyntaxException, IOException {
HttpClient client = HttpClients.createDefault();
try {
establishTopology(client, baseURL, container, cache, timeout, nodes);
} finally {
HttpClientUtils.closeQuietly(client);
}
}
public static void establishTopology(HttpClient client, URL baseURL, String container, String cache, long timeout, String... nodes)
throws URISyntaxException, IOException {
URI uri = TopologyChangeListenerServlet.createURI(baseURL, container, cache, timeout, nodes);
HttpResponse response = client.execute(new HttpGet(uri));
try {
assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
} finally {
HttpClientUtils.closeQuietly(response);
}
}
/**
* Tries a get on the provided client with default GRACE_TIME_TO_MEMBERSHIP_CHANGE.
*/
public static HttpResponse tryGet(final HttpClient client, final String url) throws IOException {
return tryGet(client, url, GRACE_TIME_TO_REPLICATE);
}
public static HttpResponse tryGet(final HttpClient client, final HttpUriRequest r) throws IOException {
final long startTime;
HttpResponse response = client.execute(r);
startTime = System.currentTimeMillis();
while(response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK && startTime + GRACE_TIME_TO_REPLICATE > System.currentTimeMillis()) {
response = client.execute(r);
}
return response;
}
/**
* Tries a get on the provided client with specified graceTime in milliseconds.
*/
public static HttpResponse tryGet(final HttpClient client, final String url, final long graceTime) throws IOException {
return tryGet(client, new HttpGet(url));
}
/**
* Tries a get on the provided client consuming the request body.
*/
public static String tryGetAndConsume(final HttpClient client, final String url) throws IOException {
// Get the response
HttpResponse response = tryGet(client, url);
// Consume it
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8), 4096)) {
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
return sb.toString();
}
/**
* Utility class.
*/
private ClusterHttpClientUtil() {
}
}
| 4,884
| 38.715447
| 157
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/NodeNameGetter.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.clustering;
/**
* @author Ondrej Chaloupka
*/
public class NodeNameGetter {
private NodeNameGetter() {
}
public static String getNodeName() {
return System.getProperty("jboss.node.name");
}
}
| 1,271
| 33.378378
| 70
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/ClusterDatabaseTestUtil.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, 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;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.DB_PORT;
import java.sql.SQLException;
import org.h2.tools.Server;
/**
* Simple test utility to start/stop an external H2 database, e.g. to be used in clustering tests which use a shared database.
* Database files are stored in ${project.build.directory}/target/h2 directory.
*
* @author Radoslav Husar
*/
public class ClusterDatabaseTestUtil {
public static void startH2() throws SQLException {
Server.createTcpServer("-tcpPort", DB_PORT, "-tcpAllowOthers", "-ifNotExists", "-tcpPassword", "sa", "-baseDir", "./target/h2").start();
}
public static void stopH2() throws SQLException {
Server.shutdownTcpServer("tcp://localhost:" + DB_PORT, "sa", true, true);
}
private ClusterDatabaseTestUtil() {
// Utility class
}
}
| 1,918
| 36.627451
| 144
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/ClusterTestUtil.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.clustering;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.util.PropertyPermission;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.clustering.ejb.EJBDirectory;
import org.jboss.as.test.integration.management.util.CLITestUtil;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.container.ClassContainer;
import org.jboss.shrinkwrap.api.container.ManifestContainer;
import org.junit.Assert;
/**
* Utility class for clustering tests.
*
* @author Radoslav Husar
*/
public class ClusterTestUtil {
public static <A extends Archive<A> & ClassContainer<A> & ManifestContainer<A>> A addTopologyListenerDependencies(A archive) {
archive.addClasses(TopologyChangeListener.class, TopologyChangeListenerBean.class, TopologyChangeListenerServlet.class);
archive.setManifest(new StringAsset("Manifest-Version: 1.0\nDependencies: org.infinispan\n"));
archive.addAsManifestResource(createPermissionsXmlAsset(new RuntimePermission("getClassLoader"), new PropertyPermission("jboss.node.name", "read")), "permissions.xml");
return archive;
}
public static void establishTopology(EJBDirectory directory, String container, String cache, String... nodes) throws Exception {
TopologyChangeListener listener = directory.lookupStateless(TopologyChangeListenerBean.class, TopologyChangeListener.class);
listener.establishTopology(container, cache, TopologyChangeListener.DEFAULT_TIMEOUT, nodes);
}
// Model management convenience methods
public static ModelNode execute(ManagementClient client, String request) throws Exception {
ModelNode operation = CLITestUtil.getCommandContext().buildRequest(request);
ModelNode result = client.getControllerClient().execute(operation);
Assert.assertEquals(result.toString(), ModelDescriptionConstants.SUCCESS, result.get(ModelDescriptionConstants.OUTCOME).asStringOrNull());
return result.get(ModelDescriptionConstants.RESULT);
}
private ClusterTestUtil() {
}
}
| 3,337
| 46.685714
| 176
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/TopologyChangeListenerBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, 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;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import jakarta.ejb.Remote;
import jakarta.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.infinispan.Cache;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.distribution.LocalizedCacheTopology;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.Listener.Observation;
import org.infinispan.notifications.cachelistener.annotation.TopologyChanged;
import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent;
import org.infinispan.util.concurrent.BlockingManager;
import org.jboss.logging.Logger;
/**
* Jakarta Enterprise Beans that establishes a stable topology.
* @author Paul Ferraro
*/
@Stateless
@Remote(TopologyChangeListener.class)
@Listener(observation = Observation.POST)
public class TopologyChangeListenerBean implements TopologyChangeListener, Runnable {
private static final Logger logger = Logger.getLogger(TopologyChangeListenerBean.class);
@Override
public void establishTopology(String containerName, String cacheName, long timeout, String... nodes) throws InterruptedException {
Set<String> expectedMembers = Stream.of(nodes).collect(Collectors.toSet());
Cache<?, ?> cache = findCache(containerName, cacheName);
if (cache == null) {
throw new IllegalStateException(String.format("Cache %s.%s not found", containerName, cacheName));
}
cache.addListener(this);
try {
synchronized (this) {
DistributionManager dist = cache.getAdvancedCache().getDistributionManager();
LocalizedCacheTopology topology = dist.getCacheTopology();
Set<String> members = getMembers(topology);
long start = System.currentTimeMillis();
long now = start;
long endTime = start + timeout;
while (!expectedMembers.equals(members)) {
logger.infof("%s != %s, waiting for a topology change event. Current topology id = %d", expectedMembers, members, topology.getTopologyId());
this.wait(endTime - now);
now = System.currentTimeMillis();
if (now >= endTime) {
throw new InterruptedException(String.format("Cache %s/%s failed to establish view %s within %d ms. Current view is: %s", containerName, cacheName, expectedMembers, timeout, members));
}
topology = dist.getCacheTopology();
members = getMembers(topology);
}
logger.infof("Cache %s/%s successfully established view %s within %d ms. Topology id = %d", containerName, cacheName, expectedMembers, now - start, topology.getTopologyId());
}
} finally {
cache.removeListener(this);
}
}
private static Cache<?, ?> findCache(String containerName, String cacheName) {
try {
Context context = new InitialContext();
try {
EmbeddedCacheManager manager = (EmbeddedCacheManager) context.lookup("java:jboss/infinispan/container/" + containerName);
return manager.cacheExists(cacheName) ? manager.getCache(cacheName) : null;
} finally {
context.close();
}
} catch (NamingException e) {
return null;
}
}
private static Set<String> getMembers(LocalizedCacheTopology topology) {
return topology.getMembers().stream().map(Object::toString).sorted().collect(Collectors.toSet());
}
@TopologyChanged
public CompletionStage<Void> topologyChanged(TopologyChangedEvent<?, ?> event) {
@SuppressWarnings("deprecation")
BlockingManager blocking = event.getCache().getCacheManager().getGlobalComponentRegistry().getComponent(BlockingManager.class);
blocking.asExecutor(this.getClass().getName()).execute(this);
return CompletableFuture.completedFuture(null);
}
@Override
public void run() {
synchronized (this) {
this.notify();
}
}
}
| 5,484
| 43.233871
| 209
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/TopologyChangeListenerServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, 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;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import jakarta.ejb.EJB;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Utility servlet that delegates to an Jakarta Enterprise Beans to perform topology stabilization.
* @author Paul Ferraro
*/
@WebServlet(urlPatterns = { TopologyChangeListenerServlet.SERVLET_PATH })
public class TopologyChangeListenerServlet extends HttpServlet {
private static final long serialVersionUID = -4382952409558738642L;
private static final String SERVLET_NAME = "membership";
static final String SERVLET_PATH = "/" + SERVLET_NAME;
private static final String CONTAINER = "container";
private static final String CACHE = "cache";
private static final String NODES = "nodes";
private static final String TIMEOUT = "timeout";
public static URI createURI(URL baseURL, String container, String cache, long timeout, String... nodes) throws URISyntaxException {
StringBuilder builder = new StringBuilder(baseURL.toURI().resolve(SERVLET_NAME).toString());
builder.append('?').append(CONTAINER).append('=').append(container);
builder.append('&').append(CACHE).append('=').append(cache);
builder.append('&').append(TIMEOUT).append('=').append(timeout);
for (String node: nodes) {
builder.append('&').append(NODES).append('=').append(node);
}
return URI.create(builder.toString());
}
@EJB
private TopologyChangeListener listener;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String container = getRequiredParameter(request, CONTAINER);
String cache = getRequiredParameter(request, CACHE);
String[] nodes = request.getParameterValues(NODES);
long timeout = parseLong(getRequiredParameter(request, TIMEOUT));
try {
this.listener.establishTopology(container, cache, timeout, nodes);
} catch (InterruptedException e) {
throw new ServletException(e);
}
}
private static String getRequiredParameter(HttpServletRequest request, String name) throws ServletException {
String value = request.getParameter(name);
if (value == null) {
throw new ServletException(String.format("No '%s' parameter specified", name));
}
return value;
}
private static long parseLong(String value) throws ServletException {
try {
return Long.parseLong(value);
} catch (NumberFormatException e) {
throw new ServletException(String.format("Value '%s' cannot be parsed to long.", value), e);
}
}
}
| 3,993
| 41.042105
| 135
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/EJBClientContextSelector.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.clustering;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.jboss.ejb.client.EJBClientContext;
/**
* @author Paul Ferraro
*/
public class EJBClientContextSelector {
public static EJBClientContext setup(String file) throws IOException {
return setup(file, null);
}
public static EJBClientContext setup(String file, Properties propertiesToReplace) throws IOException {
// setUp the selector
final InputStream inputStream = EJBClientContextSelector.class.getClassLoader().getResourceAsStream(file);
if (inputStream == null) {
throw new IllegalStateException("Could not find " + file + " in classpath");
}
final Properties properties = new Properties();
properties.load(inputStream);
// add or replace properties passed from file
if (propertiesToReplace != null) {
properties.putAll(propertiesToReplace);
}
// TODO Elytron: Once support for legacy EJB properties has been added back, actually set the EJB properties
// that should be used for this test using properties
return null;
}
}
| 2,233
| 37.517241
| 116
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/NodeUtil.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, 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;
import java.util.Set;
import org.jboss.arquillian.container.test.api.ContainerController;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.as.arquillian.api.WildFlyContainerController;
import org.jboss.logging.Logger;
/**
* Utility class to start and stop containers and/or deployments.
*
* @author Radoslav Husar
*/
public final class NodeUtil {
private static final Logger log = Logger.getLogger(NodeUtil.class);
public static void deploy(Deployer deployer, Set<String> deployments) {
for (String deployment : deployments) {
deploy(deployer, deployment);
}
}
public static void deploy(Deployer deployer, String deployment) {
log.tracef("Deploying %s", deployment);
deployer.deploy(deployment);
log.tracef("Deployed %s", deployment);
}
public static void undeploy(Deployer deployer, Set<String> deployments) {
for (String deployment : deployments) {
undeploy(deployer, deployment);
}
}
public static void undeploy(Deployer deployer, String deployment) {
log.tracef("Undeploying %s", deployment);
deployer.undeploy(deployment);
log.tracef("Undeployed %s", deployment);
}
public static void start(ContainerController controller, Set<String> containers) {
// TODO do this in parallel.
for (String container : containers) {
start(controller, container);
}
}
public static void start(ContainerController controller, String container) {
if (!controller.isStarted(container)) {
log.tracef("Starting container %s", container);
controller.start(container);
log.tracef("Started container %s", container);
} else {
log.tracef("Container %s was already started", container);
}
}
public static void stop(ContainerController controller, Set<String> containers) {
for (String container : containers) {
stop(controller, container);
}
}
public static void stop(ContainerController controller, String container) {
if (controller.isStarted(container)) {
log.tracef("Stopping container %s", container);
controller.stop(container);
log.tracef("Stopped container %s", container);
} else {
log.tracef("Container %s was already stopped", container);
}
}
public static boolean isStarted(ContainerController controller, String container) {
return controller.isStarted(container);
}
public static void stop(WildFlyContainerController controller, Set<String> containers, int timeout) {
for (String container : containers) {
stop(controller, container, timeout);
}
}
public static void stop(WildFlyContainerController controller, String container, int timeout) {
if (controller.isStarted(container)) {
log.tracef("Stopping container %s", container);
controller.stop(container, timeout);
log.tracef("Stopped container %s", container);
} else {
log.tracef("Container %s was already stopped", container);
}
}
private NodeUtil() {
}
}
| 4,329
| 35.083333
| 105
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/arquillian/StopCustomContainersOnAfterSuiteExtension.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.clustering.arquillian;
import org.jboss.arquillian.container.spi.Container;
import org.jboss.arquillian.container.spi.Container.State;
import org.jboss.arquillian.container.spi.ContainerRegistry;
import org.jboss.arquillian.container.spi.client.container.LifecycleException;
import org.jboss.arquillian.core.api.annotation.Observes;
import org.jboss.arquillian.core.spi.LoadableExtension;
import org.jboss.arquillian.test.spi.event.suite.AfterSuite;
import org.jboss.logging.Logger;
import org.kohsuke.MetaInfServices;
/**
* Arquillian extension which stops custom containers after testsuite run.
*
* @author <a href="mailto:aslak@redhat.com">Aslak Knutsen</a>
* @author Radoslav Husar
*/
@MetaInfServices(LoadableExtension.class)
public class StopCustomContainersOnAfterSuiteExtension implements LoadableExtension {
static final Logger log = Logger.getLogger(StopCustomContainersOnAfterSuiteExtension.class);
@Override
public void register(ExtensionBuilder builder) {
builder.observer(StopCustomContainers.class);
}
public static class StopCustomContainers {
public void close(@Observes AfterSuite event, ContainerRegistry registry) {
for (Container c: registry.getContainers()) {
if (c.getState() == State.STARTED && "custom".equalsIgnoreCase(c.getContainerConfiguration().getMode())) {
try {
log.tracef("Stopping custom container %s", c.getName());
// TODO workaround https://issues.jboss.org/browse/WFARQ-47
c.stop();
log.tracef("Stopped custom container %s", c.getName());
} catch (LifecycleException e) {
log.errorf("Failed to stop custom container %s: %s", c.getName(), e);
}
}
}
}
}
}
| 2,936
| 42.835821
| 122
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/arquillian/ContainerRegistryResourceProvider.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.arquillian;
import java.lang.annotation.Annotation;
import org.jboss.arquillian.container.spi.ContainerRegistry;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider;
/**
* Resource provider that exposes {@link ContainerRegistry} injection for test classes which is especially useful for manual
* mode clustering tests.
*
* @author Radoslav Husar
*/
public class ContainerRegistryResourceProvider implements ResourceProvider {
@Inject
private Instance<ContainerRegistry> containerRegistryInstance;
@Override
public boolean canProvide(Class<?> type) {
return type.isAssignableFrom(ContainerRegistry.class);
}
@Override
public Object lookup(ArquillianResource resource, Annotation... qualifiers) {
return this.containerRegistryInstance.get();
}
}
| 2,044
| 36.87037
| 124
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/arquillian/ContainerRegistryResourceProviderLoadableExtension.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.arquillian;
import org.jboss.arquillian.core.spi.LoadableExtension;
import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider;
import org.kohsuke.MetaInfServices;
/**
* Arquillian loadable extension which registers {@link ContainerRegistryResourceProvider}.
*
* @author Radoslav Husar
*/
@MetaInfServices(LoadableExtension.class)
public class ContainerRegistryResourceProviderLoadableExtension implements LoadableExtension {
@Override
public void register(ExtensionBuilder builder) {
builder.service(ResourceProvider.class, ContainerRegistryResourceProvider.class);
}
}
| 1,672
| 38.833333
| 94
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/ejb/LocalEJBDirectory.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.clustering.ejb;
import java.util.Properties;
import javax.naming.NamingException;
/**
* {@link EJBDirectory} that uses local JNDI.
* @author Paul Ferraro
*/
public class LocalEJBDirectory extends NamingEJBDirectory {
public LocalEJBDirectory(String module) throws NamingException {
this(module, new Properties());
}
public LocalEJBDirectory(String module, Properties properties) throws NamingException {
super(properties, "java:app", module, "java:comp/UserTransaction");
}
public <T> T lookupStateful(Class<T> beanClass) throws Exception {
return this.lookupStateful(beanClass, beanClass);
}
public <T> T lookupStateless(Class<T> beanClass) throws Exception {
return this.lookupStateless(beanClass, beanClass);
}
public <T> T lookupSingleton(Class<T> beanClass) throws Exception {
return this.lookupSingleton(beanClass, beanClass);
}
}
| 1,978
| 34.981818
| 91
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/ejb/ClientEJBDirectory.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.clustering.ejb;
import jakarta.ejb.EJBHome;
import jakarta.transaction.UserTransaction;
import org.jboss.ejb.client.EJBClient;
import org.jboss.ejb.client.EJBHomeLocator;
import org.jboss.ejb.client.StatelessEJBLocator;
import org.wildfly.transaction.client.RemoteTransactionContext;
/**
* {@link EJBDirectory} that uses the Jakarta Enterprise Beans client API.
* @author Paul Ferraro
*/
public class ClientEJBDirectory implements EJBDirectory {
private final String appName;
private final String moduleName;
public ClientEJBDirectory(String moduleName) {
this("", moduleName);
}
public ClientEJBDirectory(String appName, String moduleName) {
this.appName = appName;
this.moduleName = moduleName;
}
@Override
public <T> T lookupStateful(String beanName, Class<T> beanInterface) throws Exception {
return EJBClient.createSessionProxy(this.createStatelessLocator(beanName, beanInterface));
}
@Override
public <T> T lookupStateless(String beanName, Class<T> beanInterface) {
return EJBClient.createProxy(this.createStatelessLocator(beanName, beanInterface));
}
@Override
public <T> T lookupSingleton(String beanName, Class<T> beanInterface) {
return EJBClient.createProxy(this.createStatelessLocator(beanName, beanInterface));
}
private <T> StatelessEJBLocator<T> createStatelessLocator(String beanName, Class<T> beanInterface) {
return new StatelessEJBLocator<>(beanInterface, this.appName, this.moduleName, beanName);
}
@Override
public <T extends EJBHome> T lookupHome(String beanName, Class<T> homeInterface) {
return EJBClient.createProxy(new EJBHomeLocator<>(homeInterface, this.appName, this.moduleName, beanName));
}
@Override
public UserTransaction lookupUserTransaction() {
return RemoteTransactionContext.getInstance().getUserTransaction();
}
@Override
public void close() {
// Do nothing
}
}
| 3,050
| 35.321429
| 115
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/ejb/EJBDirectory.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.clustering.ejb;
import jakarta.ejb.EJBHome;
import jakarta.ejb.SessionBean;
import jakarta.transaction.UserTransaction;
/**
* Jakarta Enterprise Beans lookup helper
*
* @author Paul Ferraro
*/
public interface EJBDirectory extends AutoCloseable {
<T> T lookupStateful(String beanName, Class<T> beanInterface) throws Exception;
default <T> T lookupStateful(Class<? extends T> beanClass, Class<T> beanInterface) throws Exception {
return this.lookupStateful(beanClass.getSimpleName(), beanInterface);
}
<T> T lookupStateless(String beanName, Class<T> beanInterface) throws Exception;
default <T> T lookupStateless(Class<? extends T> beanClass, Class<T> beanInterface) throws Exception {
return this.lookupStateless(beanClass.getSimpleName(), beanInterface);
}
<T> T lookupSingleton(String beanName, Class<T> beanInterface) throws Exception;
default <T> T lookupSingleton(Class<? extends T> beanClass, Class<T> beanInterface) throws Exception {
return this.lookupSingleton(beanClass.getSimpleName(), beanInterface);
}
<T extends EJBHome> T lookupHome(String beanName, Class<T> homeInterface) throws Exception;
default <T extends EJBHome> T lookupHome(Class<? extends SessionBean> beanClass, Class<T> homeInterface) throws Exception {
return this.lookupHome(beanClass.getSimpleName(), homeInterface);
}
UserTransaction lookupUserTransaction() throws Exception;
@Override
void close() throws Exception;
}
| 2,557
| 38.96875
| 127
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/ejb/NamingEJBDirectory.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.clustering.ejb;
import java.util.Properties;
import jakarta.ejb.EJBHome;
import jakarta.ejb.SessionBean;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jakarta.transaction.UserTransaction;
/**
* Abstract JNDI-based {@link EJBDirectory}.
* @author Paul Ferraro
*/
public abstract class NamingEJBDirectory implements EJBDirectory {
private final Context context;
private final String prefix;
private final String moduleName;
private final String txContextName;
protected enum Type {
STATEFUL, STATELESS, SINGLETON, HOME
}
protected NamingEJBDirectory(Properties env, String prefix, String moduleName, String txContextName) throws NamingException {
this(new InitialContext(env), prefix, moduleName, txContextName);
}
protected NamingEJBDirectory(InitialContext context, String prefix, String moduleName, String txContextName) {
this.context = context;
this.prefix = prefix;
this.moduleName = moduleName;
this.txContextName = txContextName;
}
@Override
public void close() throws NamingException {
this.context.close();
}
@Override
public <T> T lookupStateful(Class<? extends T> beanClass, Class<T> beanInterface) throws NamingException {
return this.lookupStateful(beanClass.getSimpleName(), beanInterface);
}
@Override
public <T> T lookupStateless(Class<? extends T> beanClass, Class<T> beanInterface) throws NamingException {
return this.lookupStateless(beanClass.getSimpleName(), beanInterface);
}
@Override
public <T> T lookupSingleton(Class<? extends T> beanClass, Class<T> beanInterface) throws NamingException {
return this.lookupSingleton(beanClass.getSimpleName(), beanInterface);
}
@Override
public <T extends EJBHome> T lookupHome(Class<? extends SessionBean> beanClass, Class<T> homeInterface) throws NamingException {
return this.lookupHome(beanClass.getSimpleName(), homeInterface);
}
@Override
public <T> T lookupStateful(String beanName, Class<T> beanInterface) throws NamingException {
return this.lookup(beanName, beanInterface, Type.STATEFUL);
}
@Override
public <T> T lookupStateless(String beanName, Class<T> beanInterface) throws NamingException {
return this.lookup(beanName, beanInterface, Type.STATELESS);
}
@Override
public <T> T lookupSingleton(String beanName, Class<T> beanInterface) throws NamingException {
return this.lookup(beanName, beanInterface, Type.SINGLETON);
}
@Override
public <T extends EJBHome> T lookupHome(String beanName, Class<T> homeInterface) throws NamingException {
return this.lookup(beanName, homeInterface, Type.HOME);
}
@Override
public UserTransaction lookupUserTransaction() throws NamingException {
return this.lookup(this.txContextName, UserTransaction.class);
}
protected <T> T lookup(String beanName, Class<T> beanInterface, Type type) throws NamingException {
return this.lookup(this.createJndiName(beanName, beanInterface, type), beanInterface);
}
protected String createJndiName(String beanName, Class<?> beanInterface, Type type) {
return String.format("%s/%s/%s!%s", this.prefix, this.moduleName, beanName, beanInterface.getName());
}
protected <T> T lookup(String name, Class<T> targetClass) throws NamingException {
return targetClass.cast(this.context.lookup(name));
}
}
| 4,608
| 36.778689
| 132
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/ejb/RemoteEJBDirectory.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.clustering.ejb;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingException;
/**
* {@link EJBDirectory} that uses remote JNDI.
*
* NOTE:
* if you hold a static reference to this class, it causes any JNDI lookups across different tests to use the same discovered node registry (DNR).
* This can cause server starts and stops in one test to contaminate other tests and produce incorrect results.
* It is adviseable to use one instance per test by defining a @Before and @After method to create and dispose of the instance on a per test basis.
*
* @author Paul Ferraro
*/
public class RemoteEJBDirectory extends NamingEJBDirectory {
private static Properties createEnvironment() {
Properties env = new Properties();
env.setProperty(Context.INITIAL_CONTEXT_FACTORY, org.wildfly.naming.client.WildFlyInitialContextFactory.class.getName());
// TODO UserTransaction lookup currently requires environment to be configured with provider URLs.
// env.setProperty(Context.PROVIDER_URL, String.join(",", EJBClientContext.getCurrent().getConfiguredConnections().stream().map(EJBClientConnection::getDestination).map(URI::toString).collect(Collectors.toList())));
return env;
}
public RemoteEJBDirectory(String module) throws NamingException {
this(module, createEnvironment());
}
public RemoteEJBDirectory(String module, Properties properties) throws NamingException {
super(properties, "ejb:", module, "txn:UserTransaction");
}
@Override
protected String createJndiName(String beanName, Class<?> beanInterface, Type type) {
String jndiName = super.createJndiName(beanName, beanInterface, type);
switch (type) {
case STATEFUL: {
return jndiName + "?stateful=true";
}
default: {
return jndiName;
}
}
}
}
| 2,986
| 41.070423
| 223
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/web/Mutable.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, 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.single.web;
import java.io.IOException;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger;
public class Mutable implements Serializable {
private static final long serialVersionUID = -5129400250276547619L;
private transient boolean serialized = false;
private final AtomicInteger value;
public Mutable(int value) {
this.value = new AtomicInteger(value);
}
public int increment() {
return this.value.incrementAndGet();
}
@Override
public String toString() {
return String.valueOf(this.value.get());
}
public boolean wasSerialized() {
return this.serialized;
}
@Override
public int hashCode() {
return this.value.get();
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Mutable)) return false;
return this.value.get() == ((Mutable) object).value.get();
}
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
this.serialized = true;
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
this.serialized = true;
}
}
| 2,332
| 32.328571
| 102
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/web/SimpleWebTestCase.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.clustering.single.web;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
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.PathElement;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.http.util.TestHttpClientUtils;
import org.jboss.as.test.shared.ManagementServerSetupTask;
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;
/**
* Validate the <distributable/> works for single node.
*
* @author Paul Ferraro
*/
@RunWith(Arquillian.class)
@ServerSetup(SimpleWebTestCase.ServerSetupTask.class)
public class SimpleWebTestCase {
private static final String MODULE_NAME = SimpleWebTestCase.class.getSimpleName();
private static final String APPLICATION_NAME = MODULE_NAME + ".war";
@Deployment(name = DEPLOYMENT_1, testable = false)
public static Archive<?> deployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, APPLICATION_NAME);
war.addClasses(SimpleServlet.class, Mutable.class);
war.setWebXML(SimpleWebTestCase.class.getPackage(), "web.xml");
return war;
}
@Test
@OperateOnDeployment(DEPLOYMENT_1)
public void test(@ArquillianResource(SimpleServlet.class) URL baseURL, @ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) ManagementClient managementClient) throws IOException, URISyntaxException {
// Validate existence of runtime resource for deployment cache
PathAddress address = PathAddress.pathAddress(PathElement.pathElement("subsystem", "infinispan"), PathElement.pathElement("cache-container", "web"), PathElement.pathElement("cache", APPLICATION_NAME));
ModelNode operation = Util.createOperation(ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION, address);
operation.get(ModelDescriptionConstants.NAME).set(new ModelNode("number-of-entries"));
ModelNode result = managementClient.getControllerClient().execute(operation);
Assert.assertEquals(0, result.get(ModelDescriptionConstants.RESULT).asInt());
URI uri = SimpleServlet.createURI(baseURL);
try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
HttpResponse response = client.execute(new HttpGet(uri));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue()));
Assert.assertFalse(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
} finally {
HttpClientUtils.closeQuietly(response);
}
response = client.execute(new HttpGet(uri));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader("value").getValue()));
// This won't be true unless we have somewhere to which to replicate or session persistence is configured (current default)
Assert.assertFalse(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
} finally {
HttpClientUtils.closeQuietly(response);
}
}
result = managementClient.getControllerClient().execute(operation);
Assert.assertNotEquals(0, result.get(ModelDescriptionConstants.RESULT).asInt());
}
public static class ServerSetupTask extends ManagementServerSetupTask {
public ServerSetupTask() {
super("single", createContainerConfigurationBuilder()
.setupScript(createScriptBuilder()
.startBatch()
// Switch to primary-owner routing to validate WFLY-18095
.add("/subsystem=infinispan/cache-container=web/local-cache=routing:add")
.add("/subsystem=distributable-web/routing=infinispan:add(cache-container=web, cache=routing)")
.add("/subsystem=distributable-web/infinispan-session-management=default/affinity=primary-owner:add")
.endBatch()
.add("/subsystem=infinispan/cache-container=web/local-cache=passivation:write-attribute(name=statistics-enabled, value=true)")
.build())
.tearDownScript(createScriptBuilder()
.add("/subsystem=infinispan/cache-container=web/local-cache=passivation:undefine-attribute(name=statistics-enabled)")
.startBatch()
.add("/subsystem=distributable-web/infinispan-session-management=default/affinity=local:add")
.add("/subsystem=distributable-web/routing=local:add")
.add("/subsystem=infinispan/cache-container=web/local-cache=routing:remove")
.endBatch()
.build())
.build());
}
}
}
| 7,120
| 50.601449
| 209
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/web/SimpleServlet.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.clustering.single.web;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.function.Function;
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;
/**
* @author Paul Ferraro
*/
@WebServlet(urlPatterns = { SimpleServlet.SERVLET_PATH })
public class SimpleServlet extends HttpServlet {
private static final long serialVersionUID = -592774116315946908L;
private static final String SERVLET_NAME = "simple";
static final String SERVLET_PATH = "/" + SERVLET_NAME;
public static final String REQUEST_DURATION_PARAM = "requestduration";
public static final String HEADER_SERIALIZED = "serialized";
public static final String VALUE_HEADER = "value";
public static final String SESSION_ID_HEADER = "sessionId";
public static final String ATTRIBUTE = "test";
public static final String HEADER_NODE_NAME = "nodename";
public static URI createURI(URL baseURL) throws URISyntaxException {
return createURI(baseURL.toURI());
}
public static URI createURI(URI baseURI) {
return baseURI.resolve(SERVLET_NAME);
}
public static URI createURI(URL baseURL, int requestDuration) throws URISyntaxException {
return createURI(baseURL.toURI(), requestDuration);
}
public static URI createURI(URI baseURI, int requestDuration) {
return baseURI.resolve(SERVLET_NAME + '?' + REQUEST_DURATION_PARAM + '=' + requestDuration);
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String query = request.getQueryString();
this.getServletContext().log(String.format("[%s] %s%s", request.getMethod(), request.getRequestURI(), (query != null) ? '?' + query : ""));
super.service(request, response);
}
@Override
protected void doHead(HttpServletRequest request, HttpServletResponse response) throws IOException {
HttpSession session = request.getSession(false);
if (session != null) {
response.addHeader(SESSION_ID_HEADER, session.getId());
}
}
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
response.addHeader(SESSION_ID_HEADER, session.getId());
session.removeAttribute(ATTRIBUTE);
}
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
Function<HttpSession, Mutable> accessor = session -> {
Mutable mutable = (Mutable) session.getAttribute(ATTRIBUTE);
if (mutable == null) {
mutable = new Mutable(0);
session.setAttribute(ATTRIBUTE, mutable);
}
return mutable;
};
this.increment(request, response, accessor);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Function<HttpSession, Mutable> accessor = session -> {
Mutable mutable = (Mutable) session.getAttribute(ATTRIBUTE);
if (mutable == null) {
session.setAttribute(ATTRIBUTE, new Mutable(0));
}
return (mutable == null) ? (Mutable) session.getAttribute(ATTRIBUTE) : mutable;
};
this.increment(request, response, accessor);
}
private void increment(HttpServletRequest request, HttpServletResponse response, Function<HttpSession, Mutable> accessor) throws IOException {
HttpSession session = request.getSession(true);
response.addHeader(SESSION_ID_HEADER, session.getId());
Mutable mutable = accessor.apply(session);
int value = mutable.increment();
response.setIntHeader(VALUE_HEADER, value);
response.setHeader(HEADER_SERIALIZED, Boolean.toString(mutable.wasSerialized()));
Mutable current = (Mutable) session.getAttribute(ATTRIBUTE);
if (!mutable.equals(current)) {
throw new IllegalStateException(String.format("Session attribute value = %s, expected %s", current, mutable));
}
try {
String nodeName = System.getProperty("jboss.node.name");
response.setHeader(HEADER_NODE_NAME, nodeName);
} catch (Exception ignore) {
}
this.getServletContext().log(request.getRequestURI() + ", value = " + value);
// Long running request?
if (request.getParameter(REQUEST_DURATION_PARAM) != null) {
int duration = Integer.parseInt(request.getParameter(REQUEST_DURATION_PARAM));
try {
Thread.sleep(duration);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
response.getWriter().write("Success");
}
}
| 6,490
| 40.082278
| 147
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/web/NonHaWebSessionPersistenceTestCase.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.clustering.single.web;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.CONTAINER_SINGLE;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.DEPLOYMENT_1;
import java.net.URI;
import java.net.URL;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.CloseableHttpClient;
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.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.WildFlyContainerController;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.clustering.ClusterTestUtil;
import org.jboss.as.test.clustering.NodeUtil;
import org.jboss.as.test.http.util.TestHttpClientUtils;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Validates that session passivation in non-HA environment works (on single node).
*
* @author Radoslav Husar
*/
@RunWith(Arquillian.class)
public class NonHaWebSessionPersistenceTestCase {
private static final String MODULE_NAME = NonHaWebSessionPersistenceTestCase.class.getSimpleName();
private static final String APPLICATION_NAME = MODULE_NAME + ".war";
@ArquillianResource
private WildFlyContainerController controller;
@ArquillianResource
private Deployer deployer;
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
public static Archive<?> deployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, APPLICATION_NAME);
war.addClasses(SimpleServlet.class, Mutable.class);
war.setWebXML(NonHaWebSessionPersistenceTestCase.class.getPackage(), "web.xml");
return war;
}
@Before
public void beforeTestMethod() {
NodeUtil.start(this.controller, CONTAINER_SINGLE);
NodeUtil.deploy(this.deployer, DEPLOYMENT_1);
}
@After
public void afterTestMethod() {
NodeUtil.undeploy(this.deployer, DEPLOYMENT_1);
NodeUtil.stop(this.controller, CONTAINER_SINGLE);
}
@Test
public void testSessionPersistence(@ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL, @ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) ManagementClient managementClient) throws Exception {
URI url = SimpleServlet.createURI(baseURL);
try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
String sessionId = null;
try (CloseableHttpResponse response = client.execute(new HttpGet(url))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue()));
sessionId = response.getFirstHeader(SimpleServlet.SESSION_ID_HEADER).getValue();
}
try (CloseableHttpResponse response = client.execute(new HttpGet(url))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader("value").getValue()));
Assert.assertFalse(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
Assert.assertEquals(sessionId, response.getFirstHeader(SimpleServlet.SESSION_ID_HEADER).getValue());
}
NodeUtil.stop(this.controller, CONTAINER_SINGLE);
NodeUtil.start(this.controller, CONTAINER_SINGLE);
if (Boolean.getBoolean("ts.bootable") || Boolean.getBoolean("ts.bootable.ee9")) {
NodeUtil.deploy(this.deployer, DEPLOYMENT_1);
}
try (CloseableHttpResponse response = client.execute(new HttpGet(url))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("Session passivation was configured but session was lost after restart.",
3, Integer.parseInt(response.getFirstHeader("value").getValue()));
Assert.assertTrue(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
Assert.assertEquals(sessionId, response.getFirstHeader(SimpleServlet.SESSION_ID_HEADER).getValue());
}
String invalidationRequest = String.format("/deployment=%s/subsystem=undertow:invalidate-session(session-id=%s)", APPLICATION_NAME, sessionId);
ClusterTestUtil.execute(managementClient, invalidationRequest);
try (CloseableHttpResponse response = client.execute(new HttpHead(url))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertFalse(response.containsHeader(SimpleServlet.SESSION_ID_HEADER));
}
}
}
}
| 6,458
| 46.844444
| 236
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/web/shared/NonDistributableSharedSessionTestCase.java
|
/*
*
* Copyright 2019 Red Hat, Inc.
*
* 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.jboss.as.test.clustering.single.web.shared;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.DEPLOYMENT_1;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
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.test.clustering.cluster.web.AbstractWebFailoverTestCase;
import org.jboss.as.test.clustering.single.web.Mutable;
import org.jboss.as.test.clustering.single.web.SimpleServlet;
import org.jboss.as.test.http.util.TestHttpClientUtils;
import org.jboss.as.test.shared.ServerReload;
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;
/**
* Validates that web applications within an ear can share sessions if configured appropriately, but that its sessions are non-distributable.
* @author Martin Simka
*/
@RunWith(Arquillian.class)
public class NonDistributableSharedSessionTestCase {
private static final String MODULE = NonDistributableSharedSessionTestCase.class.getSimpleName();
private static final String MODULE_1 = "war1";
private static final String MODULE_2 = "war2";
@ContainerResource
private ManagementClient managementClient;
@Deployment(name = DEPLOYMENT_1, testable = false)
public static Archive<?> deployment1() {
return getDeployment();
}
private static Archive<?> getDeployment() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, MODULE + ".jar");
jar.addClass(Mutable.class);
WebArchive war1 = ShrinkWrap.create(WebArchive.class, MODULE_1 + ".war");
war1.addClass(SimpleServlet.class);
war1.setWebXML(AbstractWebFailoverTestCase.class.getPackage(), "web.xml");
WebArchive war2 = ShrinkWrap.create(WebArchive.class, MODULE_2 + ".war");
war2.addClass(SimpleServlet.class);
war2.setWebXML(AbstractWebFailoverTestCase.class.getPackage(), "web.xml");
EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, MODULE + ".ear");
ear.addAsLibraries(jar);
ear.addAsModule(war1);
ear.addAsModule(war2);
ear.addAsManifestResource(NonDistributableSharedSessionTestCase.class.getPackage(), "jboss-all.xml", "jboss-all.xml");
return ear;
}
@Test
public void test(
@ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) URL baseURLDep)
throws URISyntaxException, IOException {
URI baseURI = new URI(baseURLDep.toExternalForm() + "/");
URI uri1 = SimpleServlet.createURI(baseURI.resolve(MODULE_1 + "/"));
URI uri2 = SimpleServlet.createURI(baseURI.resolve(MODULE_2 + "/"));
try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
int expected = 1;
try (CloseableHttpResponse response = client.execute(new HttpGet(uri1))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(expected++, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue()));
}
try (CloseableHttpResponse response = client.execute(new HttpGet(uri2))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(expected++, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue()));
}
// A distributable web application preserves its web sessions across server restarts, a non-distributable web application does not.
ServerReload.executeReloadAndWaitForCompletion(this.managementClient);
expected = 1;
try (CloseableHttpResponse response = client.execute(new HttpGet(uri1))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(expected++, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue()));
}
try (CloseableHttpResponse response = client.execute(new HttpGet(uri2))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(expected++, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue()));
}
}
}
}
| 5,771
| 45.548387
| 143
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/web/passivation/LocalCoarseSessionPassivationTestCase.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.jboss.as.test.clustering.single.web.passivation;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.*;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.junit.runner.RunWith;
/**
* Validates the correctness of session passivation events for a distributed session manager using a local, passivating cache and SESSION granularity.
* @author Paul Ferraro
*/
@RunWith(Arquillian.class)
public class LocalCoarseSessionPassivationTestCase extends LocalSessionPassivationTestCase {
private static final String MODULE_NAME = LocalCoarseSessionPassivationTestCase.class.getSimpleName();
@Deployment(name = DEPLOYMENT_1, testable = false)
public static Archive<?> deployment() {
return getBaseDeployment(MODULE_NAME).addAsWebInfResource(LocalSessionPassivationTestCase.class.getPackage(), "distributable-web-coarse.xml", "distributable-web.xml");
}
}
| 2,043
| 43.434783
| 175
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/web/passivation/LocalFineSessionPassivationTestCase.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.jboss.as.test.clustering.single.web.passivation;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.*;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.junit.runner.RunWith;
/**
* Validates the correctness of session passivation events for a distributed session manager using a local, passivating cache and ATTRIBUTE granularity.
* @author Paul Ferraro
*/
@RunWith(Arquillian.class)
public class LocalFineSessionPassivationTestCase extends LocalSessionPassivationTestCase {
private static final String MODULE_NAME = LocalFineSessionPassivationTestCase.class.getSimpleName();
@Deployment(name = DEPLOYMENT_1, testable = false)
public static Archive<?> deployment() {
return getBaseDeployment(MODULE_NAME).addAsWebInfResource(LocalSessionPassivationTestCase.class.getPackage(), "distributable-web-fine.xml", "distributable-web.xml");
}
}
| 2,039
| 43.347826
| 173
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/web/passivation/SessionOperationServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, 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.single.web.passivation;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
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 jakarta.servlet.http.HttpSessionActivationListener;
import jakarta.servlet.http.HttpSessionEvent;
@WebServlet(urlPatterns = SessionOperationServlet.SERVLET_PATH)
public class SessionOperationServlet extends HttpServlet {
private static final long serialVersionUID = -1769104491085299700L;
private static final String SERVLET_NAME = "listener";
static final String SERVLET_PATH = "/" + SERVLET_NAME;
private static final String OPERATION = "operation";
private static final String GET = "get";
private static final String SET = "set";
private static final String NAME = "name";
private static final String VALUE = "value";
public static final String RESULT = "result";
public static final String SESSION_ID = "jsessionid";
public static URI createGetURI(URL baseURL, String name) throws URISyntaxException {
StringBuilder builder = appendParameter(buildURI(GET), NAME, name);
return baseURL.toURI().resolve(builder.toString());
}
public static URI createSetURI(URL baseURL, String name, String... values) throws URISyntaxException {
StringBuilder builder = appendParameter(buildURI(SET), NAME, name);
for (String value: values) {
appendParameter(builder, VALUE, value);
}
return baseURL.toURI().resolve(builder.toString());
}
private static StringBuilder buildURI(String operation) {
return new StringBuilder(SERVLET_NAME).append('?').append(OPERATION).append('=').append(operation);
}
private static StringBuilder appendParameter(StringBuilder builder, String parameter, String value) {
return builder.append('&').append(parameter).append('=').append(value);
}
static final BlockingQueue<Map.Entry<String, EventType>> EVENTS = new LinkedBlockingQueue<>();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
String operation = getRequiredParameter(req, OPERATION);
HttpSession session = req.getSession(true);
resp.addHeader(SESSION_ID, session.getId());
switch (operation) {
case SET: {
String name = getRequiredParameter(req, NAME);
String value = req.getParameter(VALUE);
session.setAttribute(name, (value != null) ? new SessionAttributeValue(value) : null);
break;
}
case GET: {
String name = getRequiredParameter(req, NAME);
SessionAttributeValue value = (SessionAttributeValue) session.getAttribute(name);
if (value != null) {
resp.setHeader(RESULT, value.getValue());
}
break;
}
default: {
throw new ServletException("Unrecognized operation: " + operation);
}
}
List<Map.Entry<String, EventType>> events = new LinkedList<>();
if (EVENTS.drainTo(events) > 0) {
events.forEach(entry -> resp.addHeader(entry.getKey(), entry.getValue().name()));
}
}
private static String getRequiredParameter(HttpServletRequest req, String name) throws ServletException {
String value = req.getParameter(name);
if (value == null) {
throw new ServletException("Missing parameter: " + name);
}
return value;
}
public enum EventType {
PASSIVATION, ACTIVATION;
}
public static class SessionAttributeValue implements Serializable, HttpSessionActivationListener {
private static final long serialVersionUID = -8824497321979784527L;
private final String value;
public SessionAttributeValue(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
@Override
public void sessionWillPassivate(HttpSessionEvent event) {
EVENTS.add(new SimpleImmutableEntry<>(event.getSession().getId(), EventType.PASSIVATION));
}
@Override
public void sessionDidActivate(HttpSessionEvent event) {
EVENTS.add(new SimpleImmutableEntry<>(event.getSession().getId(), EventType.ACTIVATION));
}
}
}
| 5,946
| 39.455782
| 109
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/web/passivation/LocalSessionPassivationTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, 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.single.web.passivation;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.*;
import static org.junit.Assert.*;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.stream.Stream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
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.OperateOnDeployment;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.clustering.single.web.SimpleServlet;
import org.jboss.as.test.shared.TimeoutUtil;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
/**
* Validates the correctness of session activation/passivation events for a distributed session manager using a local, passivating cache.
* @author Paul Ferraro
*/
public abstract class LocalSessionPassivationTestCase {
private static final Duration MAX_PASSIVATION_DURATION = Duration.ofSeconds(TimeoutUtil.adjust(10));
static WebArchive getBaseDeployment(String moduleName) {
WebArchive war = ShrinkWrap.create(WebArchive.class, moduleName + ".war");
war.addClasses(SessionOperationServlet.class);
war.addAsWebInfResource(LocalSessionPassivationTestCase.class.getPackage(), "jboss-web.xml", "jboss-web.xml");
war.setWebXML(SimpleServlet.class.getPackage(), "web.xml");
return war;
}
@Test
public void test(@ArquillianResource(SessionOperationServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL) throws IOException, URISyntaxException {
try (CloseableHttpClient client1 = HttpClients.createDefault()) {
try (CloseableHttpClient client2 = HttpClients.createDefault()) {
String session1 = null;
// This should not trigger any passivation/activation events
try (CloseableHttpResponse response = client1.execute(new HttpGet(SessionOperationServlet.createSetURI(baseURL, "a", "1")))) {
assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
assertTrue(response.containsHeader(SessionOperationServlet.SESSION_ID));
session1 = response.getFirstHeader(SessionOperationServlet.SESSION_ID).getValue();
}
Map<String, Queue<SessionOperationServlet.EventType>> events = new HashMap<>();
Map<String, SessionOperationServlet.EventType> expectedEvents = new HashMap<>();
events.put(session1, new LinkedList<>());
expectedEvents.put(session1, SessionOperationServlet.EventType.PASSIVATION);
Instant start = Instant.now();
String session2 = null;
// This will trigger passivation of session1
try (CloseableHttpResponse response = client2.execute(new HttpGet(SessionOperationServlet.createSetURI(baseURL, "a", "2")))) {
assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
assertTrue(response.containsHeader(SessionOperationServlet.SESSION_ID));
session2 = response.getFirstHeader(SessionOperationServlet.SESSION_ID).getValue();
events.put(session2, new LinkedList<>());
expectedEvents.put(session2, SessionOperationServlet.EventType.PASSIVATION);
collectEvents(response, events);
}
// Ensure session1 was passivated
while (events.get(session1).isEmpty() && Duration.between(start, Instant.now()).compareTo(MAX_PASSIVATION_DURATION) < 0) {
try (CloseableHttpResponse response = client2.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL, "a")))) {
assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
assertTrue(response.containsHeader(SessionOperationServlet.SESSION_ID));
assertEquals(session2, response.getFirstHeader(SessionOperationServlet.SESSION_ID).getValue());
assertTrue(response.containsHeader(SessionOperationServlet.RESULT));
assertEquals("2", response.getFirstHeader(SessionOperationServlet.RESULT).getValue());
collectEvents(response, events);
}
Thread.yield();
}
assertFalse(events.get(session1).isEmpty());
validateEvents(session1, events, expectedEvents);
start = Instant.now();
// This should trigger activation of session1 and passivation of session2
try (CloseableHttpResponse response = client1.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL, "a")))) {
assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
assertTrue(response.containsHeader(SessionOperationServlet.SESSION_ID));
assertEquals(session1, response.getFirstHeader(SessionOperationServlet.SESSION_ID).getValue());
assertTrue(response.containsHeader(SessionOperationServlet.RESULT));
assertEquals("1", response.getFirstHeader(SessionOperationServlet.RESULT).getValue());
collectEvents(response, events);
assertFalse(events.get(session1).isEmpty());
assertTrue(events.get(session1).contains(SessionOperationServlet.EventType.ACTIVATION));
}
// Verify session2 was passivated
while (events.get(session2).isEmpty() && Duration.between(start, Instant.now()).compareTo(MAX_PASSIVATION_DURATION) < 0) {
try (CloseableHttpResponse response = client1.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL, "a")))) {
assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
assertTrue(response.containsHeader(SessionOperationServlet.SESSION_ID));
assertEquals(session1, response.getFirstHeader(SessionOperationServlet.SESSION_ID).getValue());
assertTrue(response.containsHeader(SessionOperationServlet.RESULT));
assertEquals("1", response.getFirstHeader(SessionOperationServlet.RESULT).getValue());
collectEvents(response, events);
}
Thread.yield();
}
assertFalse(events.get(session2).isEmpty());
validateEvents(session2, events, expectedEvents);
start = Instant.now();
// This should trigger activation of session2 and passivation of session1
try (CloseableHttpResponse response = client2.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL, "a")))) {
assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
assertTrue(response.containsHeader(SessionOperationServlet.SESSION_ID));
assertEquals(session2, response.getFirstHeader(SessionOperationServlet.SESSION_ID).getValue());
assertTrue(response.containsHeader(SessionOperationServlet.RESULT));
assertEquals("2", response.getFirstHeader(SessionOperationServlet.RESULT).getValue());
collectEvents(response, events);
assertFalse(events.get(session2).isEmpty());
assertTrue(events.get(session2).contains(SessionOperationServlet.EventType.ACTIVATION));
}
// Verify session1 was passivated
while (!events.get(session1).isEmpty() && Duration.between(start, Instant.now()).compareTo(MAX_PASSIVATION_DURATION) < 0) {
try (CloseableHttpResponse response = client2.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL, "a")))) {
assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
assertTrue(response.containsHeader(SessionOperationServlet.SESSION_ID));
assertEquals(session2, response.getFirstHeader(SessionOperationServlet.SESSION_ID).getValue());
assertTrue(response.containsHeader(SessionOperationServlet.RESULT));
assertEquals("2", response.getFirstHeader(SessionOperationServlet.RESULT).getValue());
collectEvents(response, events);
}
Thread.yield();
}
assertFalse(events.get(session1).isEmpty());
validateEvents(session1, events, expectedEvents);
validateEvents(session2, events, expectedEvents);
}
}
}
private static void collectEvents(HttpResponse response, Map<String, Queue<SessionOperationServlet.EventType>> events) {
events.entrySet().forEach((Map.Entry<String, Queue<SessionOperationServlet.EventType>> entry) -> {
String sessionId = entry.getKey();
if (response.containsHeader(sessionId)) {
Stream.of(response.getHeaders(sessionId)).forEach((Header header) -> {
entry.getValue().add(SessionOperationServlet.EventType.valueOf(header.getValue()));
});
}
});
}
private static void validateEvents(String sessionId, Map<String, Queue<SessionOperationServlet.EventType>> events, Map<String, SessionOperationServlet.EventType> expectedEvents) {
Queue<SessionOperationServlet.EventType> types = events.get(sessionId);
SessionOperationServlet.EventType type = types.poll();
SessionOperationServlet.EventType expected = expectedEvents.get(sessionId);
while (type != null) {
assertSame(expected, type);
type = types.poll();
// ACTIVATE event must follow PASSIVATE event and vice versa
expected = SessionOperationServlet.EventType.values()[(expected.ordinal() + 1) % 2];
}
expectedEvents.put(sessionId, expected);
}
}
| 11,804
| 55.483254
| 183
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/ejb/DistributableEjbSubsystemLegacyOperationTestCase.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.jboss.as.test.clustering.single.ejb;
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.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory;
import org.jboss.as.test.clustering.single.ejb.bean.Incrementor;
import org.jboss.as.test.clustering.single.ejb.bean.IncrementorBean;
import org.jboss.as.test.clustering.single.ejb.bean.Result;
import org.jboss.as.test.clustering.single.ejb.bean.StatefulIncrementorBean;
import org.jboss.as.test.clustering.ejb.EJBDirectory;
import org.jboss.as.test.shared.ManagementServerSetupTask;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Validates legacy operation of EJB deployments when <distributable-ejb/> subsystem is removed.
*
* @author Richard Achmatowicz
*/
@RunWith(Arquillian.class)
@ServerSetup(DistributableEjbSubsystemLegacyOperationTestCase.ServerSetupTask.class)
public class DistributableEjbSubsystemLegacyOperationTestCase {
private static final String MODULE_NAME = DistributableEjbSubsystemLegacyOperationTestCase.class.getSimpleName();
private static final String APPLICATION_NAME = MODULE_NAME + ".jar";
@Deployment(testable = false)
public static Archive<?> deployment() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, APPLICATION_NAME);
jar.addClasses(Result.class, Incrementor.class, IncrementorBean.class, StatefulIncrementorBean.class);
return jar;
}
@Test
public void test(@ArquillianResource ManagementClient managementClient) throws Exception {
// Confirm absence of distributable-ejb subsystem
PathAddress address = PathAddress.pathAddress(PathElement.pathElement("subsystem", "distributable-ejb"));
ModelNode operation = Util.createOperation(ModelDescriptionConstants.READ_RESOURCE_OPERATION, address);
ModelNode result = managementClient.getControllerClient().execute(operation);
Assert.assertEquals(ModelDescriptionConstants.FAILED, result.get(ModelDescriptionConstants.OUTCOME).asString());
// lookup the deployed stateful session bean
try (EJBDirectory directory = new RemoteEJBDirectory(MODULE_NAME)) {
Incrementor bean = directory.lookupStateful(StatefulIncrementorBean.class, Incrementor.class);
// invoke on the bean to check that state is maintained using legacy cache support
for (int i = 1; i <= 5; i++) {
Result<Integer> invResult = bean.increment();
Assert.assertEquals(i, invResult.getValue().intValue());
}
}
}
/*
* A server setup task that does the following:
* setup:
* - add legacy cache support to ejb3 subsystem
* - update the cache defaults to point to the legacy caches
* - remove non-legacy caches from the ejb3 subsystem
* - remove the distributable-ejb subsystem
* teardown:
* - restore distributable-ejb subsystem
* - restore non-legacy cache support
* - update the cache defaults to point again to the non-legacy caches
* - remove legacy cache support from ejb3 subsystem
*/
public static class ServerSetupTask extends ManagementServerSetupTask {
public ServerSetupTask() {
super(createContainerConfigurationBuilder()
.setupScript(createScriptBuilder()
.startBatch()
// add legacy cache support
.add("/subsystem=ejb3/cache=legacy-simple:add()")
.add("/subsystem=ejb3/passivation-store=infinispan:add(cache-container=ejb, max-size=10000")
.add("/subsystem=ejb3/cache=legacy-distributable:add(passivation-store=infinispan,aliases=[passivating,clustered])")
// update cache defaults, now to legacy caches
.add("/subsystem=ejb3:write-attribute(name=default-sfsb-cache, value=legacy-simple")
.add("/subsystem=ejb3:write-attribute(name=default-sfsb-passivation-disabled-cache, value=legacy-simple")
// remove non-legacy caches
.add("/subsystem=ejb3/simple-cache=simple:remove(){allow-resource-service-restart=true}")
.add("/subsystem=ejb3/distributable-cache=distributable:remove(){allow-resource-service-restart=true}")
// remove distributable-ejb subsystem
.add("/subsystem=distributable-ejb:remove()")
.endBatch()
.build())
.tearDownScript(createScriptBuilder()
.startBatch()
// add back distributable-ejb subsystem
.add("/subsystem=distributable-ejb:add(default-bean-management=default)")
.add("/subsystem=distributable-ejb/infinispan-bean-management=default:add(cache-container=ejb,cache=passivation,max-active-beans=10000)")
.add("/subsystem=distributable-ejb/client-mappings-registry=local:add()")
// add back non-legacy caches
.add("/subsystem=ejb3/simple-cache=simple:add()")
.add("/subsystem=ejb3/distributable-cache=distributable:add(bean-management=default)")
// reinstate cache defaults to non-legacy caches
.add("/subsystem=ejb3:write-attribute(name=default-sfsb-cache, value=simple")
.add("/subsystem=ejb3:write-attribute(name=default-sfsb-passivation-disabled-cache, value=simple")
// remove legacy cache support
.add("/subsystem=ejb3/cache=legacy-simple:remove(){allow-resource-service-restart=true}")
.add("/subsystem=ejb3/cache=legacy-distributable:remove(){allow-resource-service-restart=true}")
.add("/subsystem=ejb3/passivation-store=infinispan:remove(){allow-resource-service-restart=true}")
.endBatch()
.build())
.build());
}
}
}
| 7,877
| 54.090909
| 165
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/ejb/bean/Result.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, 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.single.ejb.bean;
import java.io.Serializable;
/**
* A wrapper for a return value that includes the node on which the result was generated.
* @author Paul Ferraro
*/
public class Result<T> implements Serializable {
private static final long serialVersionUID = -1079933234795356933L;
private final T value;
public Result(T value) {
this.value = value;
}
public T getValue() {
return this.value;
}
}
| 1,505
| 34.023256
| 89
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/ejb/bean/StatefulIncrementorBean.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.jboss.as.test.clustering.single.ejb.bean;
import jakarta.ejb.Remote;
import jakarta.ejb.Stateful;
@Stateful
@Remote(Incrementor.class)
public class StatefulIncrementorBean extends IncrementorBean {
}
| 1,237
| 38.935484
| 70
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/ejb/bean/IncrementorBean.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.jboss.as.test.clustering.single.ejb.bean;
import java.util.concurrent.atomic.AtomicInteger;
public abstract class IncrementorBean implements Incrementor {
private final AtomicInteger count = new AtomicInteger();
@Override
public Result<Integer> increment() {
return new Result<>(this.count.incrementAndGet());
}
}
| 1,377
| 38.371429
| 70
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/ejb/bean/Incrementor.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.jboss.as.test.clustering.single.ejb.bean;
import jakarta.ejb.Remove;
public interface Incrementor {
Result<Integer> increment();
@Remove
default void remove() {
// Do nothing
}
}
| 1,241
| 35.529412
| 70
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/dispatcher/CommandDispatcherTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, 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.single.dispatcher;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.NODE_1;
import static org.junit.Assert.*;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.clustering.cluster.dispatcher.bean.ClusterTopology;
import org.jboss.as.test.clustering.cluster.dispatcher.bean.ClusterTopologyRetriever;
import org.jboss.as.test.clustering.cluster.dispatcher.bean.ClusterTopologyRetrieverBean;
import org.jboss.as.test.clustering.ejb.EJBDirectory;
import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory;
import org.jboss.as.test.shared.integration.ejb.security.PermissionUtils;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Validates that a command dispatcher works in a non-clustered environment.
* @author Paul Ferraro
*/
@RunWith(Arquillian.class)
public class CommandDispatcherTestCase {
private static final String MODULE_NAME = CommandDispatcherTestCase.class.getSimpleName();
@Deployment(testable = false)
public static Archive<?> createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, MODULE_NAME + ".war");
war.addPackage(ClusterTopologyRetriever.class.getPackage());
war.addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(new RuntimePermission("getClassLoader")), "permissions.xml");
war.setWebXML(org.jboss.as.test.clustering.cluster.dispatcher.CommandDispatcherTestCase.class.getPackage(), "web.xml");
return war;
}
@Test
public void test() throws Exception {
try (EJBDirectory directory = new RemoteEJBDirectory(MODULE_NAME)) {
ClusterTopologyRetriever bean = directory.lookupStateless(ClusterTopologyRetrieverBean.class, ClusterTopologyRetriever.class);
ClusterTopology topology = bean.getClusterTopology();
assertEquals(1, topology.getNodes().size());
assertTrue(topology.getNodes().toString(), topology.getNodes().contains(NODE_1));
assertTrue(topology.getRemoteNodes().toString() + " should be empty", topology.getRemoteNodes().isEmpty());
}
}
}
| 3,364
| 47.768116
| 138
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/registry/RegistryTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, 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.single.registry;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.*;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.*;
import java.util.Collection;
import java.util.PropertyPermission;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.clustering.cluster.registry.bean.RegistryRetriever;
import org.jboss.as.test.clustering.cluster.registry.bean.RegistryRetrieverBean;
import org.jboss.as.test.clustering.ejb.EJBDirectory;
import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Validates that a registry works in a non-clustered environment.
* @author Paul Ferraro
*/
@RunWith(Arquillian.class)
public class RegistryTestCase {
private static final String MODULE_NAME = RegistryTestCase.class.getSimpleName();
@Deployment(testable = false)
public static Archive<?> createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, MODULE_NAME + ".war");
war.addPackage(RegistryRetriever.class.getPackage());
war.addAsManifestResource(createPermissionsXmlAsset(new PropertyPermission(NODE_NAME_PROPERTY, "read"), new RuntimePermission("getClassLoader")), "permissions.xml");
war.setWebXML(org.jboss.as.test.clustering.cluster.registry.RegistryTestCase.class.getPackage(), "web.xml");
return war;
}
@Test
public void test() throws Exception {
try (EJBDirectory context = new RemoteEJBDirectory(MODULE_NAME)) {
RegistryRetriever bean = context.lookupStateless(RegistryRetrieverBean.class, RegistryRetriever.class);
Collection<String> names = bean.getNodes();
assertEquals(1, names.size());
assertTrue(names.toString(), names.contains(NODE_1));
}
}
}
| 3,155
| 44.085714
| 173
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/provider/ServiceProviderRegistrationTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, 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.single.provider;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.*;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.*;
import java.util.Collection;
import java.util.PropertyPermission;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.clustering.cluster.provider.bean.ServiceProviderRetriever;
import org.jboss.as.test.clustering.cluster.provider.bean.ServiceProviderRetrieverBean;
import org.jboss.as.test.clustering.ejb.EJBDirectory;
import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Validates that a service provider registration works in a non-clustered environment.
* @author Paul Ferraro
*/
@RunWith(Arquillian.class)
public class ServiceProviderRegistrationTestCase {
private static final String MODULE_NAME = ServiceProviderRegistrationTestCase.class.getSimpleName();
@Deployment(testable = false)
public static Archive<?> createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, MODULE_NAME + ".war");
war.addPackage(ServiceProviderRetriever.class.getPackage());
war.addAsManifestResource(createPermissionsXmlAsset(new PropertyPermission(NODE_NAME_PROPERTY, "read"), new RuntimePermission("getClassLoader")), "permissions.xml");
war.setWebXML(org.jboss.as.test.clustering.cluster.provider.ServiceProviderRegistrationTestCase.class.getPackage(), "web.xml");
return war;
}
@Test
public void test() throws Exception {
try (EJBDirectory directory = new RemoteEJBDirectory(MODULE_NAME)) {
ServiceProviderRetriever bean = directory.lookupStateless(ServiceProviderRetrieverBean.class, ServiceProviderRetriever.class);
Collection<String> names = bean.getProviders();
assertEquals(1, names.size());
assertTrue(names.toString(), names.contains(NODE_1));
}
}
}
| 3,283
| 45.914286
| 173
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/infinispan/InfinispanModulesTestSuite.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 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.jboss.as.test.clustering.single.infinispan;
import org.jboss.as.test.clustering.InfinispanServerUtil;
import org.jboss.as.test.clustering.single.infinispan.cdi.embedded.GreetingCacheManagerTestCase;
import org.jboss.as.test.clustering.single.infinispan.cdi.embedded.GreetingServiceTestCase;
import org.jboss.as.test.clustering.single.infinispan.cdi.remote.RemoteGreetingServiceTestCase;
import org.jboss.as.test.clustering.single.infinispan.query.ContainerManagedHotRodClientTestCase;
import org.jboss.as.test.clustering.single.infinispan.query.HotRodClientTestCase;
import org.jboss.as.test.clustering.single.infinispan.query.ContainerRemoteQueryTestCase;
import org.jboss.as.test.clustering.single.infinispan.query.RemoteQueryTestCase;
import org.junit.ClassRule;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* JUnit suite class to support testable deployments - tests running in-container - typically to verify integration with Infinispan Modules.
* This avoids the problem of having the Infinispan Server test driver JUnit TestRule be run e.g. in-container.
* Using suite in conjunction with the @ClassRule starts the Infinispan server prior to running the tests in-container,
* as a side effect makes the execution pretty fast.
* NOTE: This doesn't work with -Dtest=... ask the @RunWith(Suite.class) is not in effect thus the @ClassRule does not invoke!
* For a workaround, to run a single test, comment out the undesired classes in this file.
*
* @author Radoslav Husar
* @since 27
*/
@RunWith(Suite.class)
@SuiteClasses({
HotRodClientTestCase.class,
RemoteQueryTestCase.class,
ContainerRemoteQueryTestCase.class,
RemoteGreetingServiceTestCase.class,
GreetingCacheManagerTestCase.class,
GreetingServiceTestCase.class,
ContainerManagedHotRodClientTestCase.class,
})
public class InfinispanModulesTestSuite {
@ClassRule
public static final TestRule INFINISPAN_SERVER_RULE = InfinispanServerUtil.INFINISPAN_SERVER_RULE;
}
| 3,140
| 47.323077
| 140
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/infinispan/cdi/remote/RemoteGreetingServiceTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 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.jboss.as.test.clustering.single.infinispan.cdi.remote;
import static org.junit.Assert.assertEquals;
import jakarta.inject.Inject;
import org.infinispan.client.hotrod.RemoteCache;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.clustering.single.infinispan.cdi.remote.deployment.RemoteGreetingCache;
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.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.spec.se.manifest.ManifestDescriptor;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test case to verify @Remote CDI injection.
*
* @author Radoslav Husar
* @since 27
*/
@RunWith(Arquillian.class)
public class RemoteGreetingServiceTestCase {
@Deployment
public static Archive<?> deployment() {
return ShrinkWrap
.create(WebArchive.class, RemoteGreetingServiceTestCase.class.getSimpleName() + ".war")
.addClass(RemoteGreetingServiceTestCase.class)
.addPackage(RemoteGreetingCache.class.getPackage())
.add(new StringAsset(Descriptors.create(ManifestDescriptor.class).attribute(
"Dependencies", "org.infinispan.commons, org.infinispan.client.hotrod, org.infinispan.cdi.common meta-inf, org.infinispan.cdi.remote meta-inf"
).exportAsString()), "META-INF/MANIFEST.MF")
.addAsWebInfResource(new StringAsset("<beans bean-discovery-mode=\"all\"></beans>"), "beans.xml")
;
}
@Inject
@RemoteGreetingCache
private RemoteCache<String, String> greetingCacheWithQualifier;
@Test
public void test() {
// A 'CLEAR' operation would fail if a cache not configured from our @Producer were to be injected
// e.g. SecurityException: ISPN006017: Operation 'CLEAR' requires authentication
greetingCacheWithQualifier.clear();
assertEquals(0, greetingCacheWithQualifier.size());
// The name set with @Remote annotation on @RemoteGreetingCache
assertEquals("transactional", greetingCacheWithQualifier.getName());
greetingCacheWithQualifier.put("Hello", this.getClass().getName());
assertEquals(1, greetingCacheWithQualifier.size());
}
}
| 3,486
| 40.511905
| 166
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/infinispan/cdi/remote/deployment/RemoteCdiConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 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.jboss.as.test.clustering.single.infinispan.cdi.remote.deployment;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.INFINISPAN_APPLICATION_PASSWORD;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.INFINISPAN_APPLICATION_USER;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.INFINISPAN_SERVER_ADDRESS;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.INFINISPAN_SERVER_PORT;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Any;
import jakarta.enterprise.inject.Disposes;
import jakarta.enterprise.inject.Produces;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.Configuration;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
/**
* This is the CDI configuration class for remote caches.
*
* @author Radoslav Husar
* @since 27
*/
public class RemoteCdiConfig {
@Produces
@ApplicationScoped
@RemoteGreetingCache
public static RemoteCacheManager defaultRemoteCacheManager() {
Configuration configuration = new ConfigurationBuilder()
.addServer().host(INFINISPAN_SERVER_ADDRESS).port(INFINISPAN_SERVER_PORT)
.security().authentication().username(INFINISPAN_APPLICATION_USER).password(INFINISPAN_APPLICATION_PASSWORD)
.build();
return new RemoteCacheManager(configuration);
}
static void stopRemoteCacheManager(@Disposes @Any RemoteCacheManager remoteCacheManager) {
remoteCacheManager.stop();
}
}
| 2,676
| 41.492063
| 124
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/infinispan/cdi/remote/deployment/RemoteGreetingCache.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 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.jboss.as.test.clustering.single.infinispan.cdi.remote.deployment;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import jakarta.inject.Qualifier;
import org.infinispan.cdi.remote.Remote;
/**
* @author Radoslav Husar
* @since 27
*/
@Remote("transactional")
@Qualifier
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RemoteGreetingCache {
}
| 1,626
| 35.977273
| 77
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/infinispan/cdi/embedded/GreetingCacheManagerTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 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.jboss.as.test.clustering.single.infinispan.cdi.embedded;
import static org.junit.Assert.assertEquals;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.clustering.single.infinispan.cdi.embedded.deployment.CdiConfig;
import org.jboss.as.test.clustering.single.infinispan.cdi.embedded.deployment.GreetingCacheManager;
import org.jboss.as.test.clustering.single.infinispan.cdi.embedded.deployment.GreetingService;
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.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.spec.se.manifest.ManifestDescriptor;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author Radoslav Husar
* @author Kevin Pollet <pollet.kevin@gmail.com> (C) 2011
* @since 27
*/
@RunWith(Arquillian.class)
public class GreetingCacheManagerTestCase {
@Inject
private GreetingService greetingService;
@Inject
private GreetingCacheManager greetingCacheManager;
@Deployment
public static Archive<?> deployment() {
return ShrinkWrap
.create(WebArchive.class, GreetingCacheManagerTestCase.class.getSimpleName() + ".war")
.addPackage(CdiConfig.class.getPackage())
.setManifest(new StringAsset(Descriptors.create(ManifestDescriptor.class).attribute("Dependencies", "org.infinispan, org.infinispan.commons, org.infinispan.cdi.common meta-inf, org.infinispan.cdi.embedded meta-inf").exportAsString()))
.addAsWebInfResource(new StringAsset("<beans bean-discovery-mode=\"all\"></beans>"), "beans.xml")
;
}
@Before
public void init() {
greetingCacheManager.clearCache();
assertEquals(0, greetingCacheManager.getNumberOfEntries());
}
@Test
public void testGreetingCacheConfiguration() {
// Cache name
assertEquals("greeting-cache", greetingCacheManager.getCacheName());
// Eviction
assertEquals(128, greetingCacheManager.getMemorySize());
// Lifespan
assertEquals(-1, greetingCacheManager.getExpirationLifespan());
}
@Test
public void testGreetingCacheCachedValues() {
greetingService.greet("Pete");
assertEquals(1, greetingCacheManager.getCachedValues().length);
assertEquals("Hello Pete :)", greetingCacheManager.getCachedValues()[0]);
}
@Test
public void testClearGreetingCache() {
greetingService.greet("Pete");
assertEquals(1, greetingCacheManager.getNumberOfEntries());
greetingCacheManager.clearCache();
assertEquals(0, greetingCacheManager.getNumberOfEntries());
}
}
| 3,953
| 36.657143
| 250
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/infinispan/cdi/embedded/GreetingServiceTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 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.jboss.as.test.clustering.single.infinispan.cdi.embedded;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.clustering.single.infinispan.cdi.embedded.deployment.CdiConfig;
import org.jboss.as.test.clustering.single.infinispan.cdi.embedded.deployment.GreetingCache;
import org.jboss.as.test.clustering.single.infinispan.cdi.embedded.deployment.GreetingService;
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.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.spec.se.manifest.ManifestDescriptor;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author Radoslav Husar
* @author Kevin Pollet <pollet.kevin@gmail.com> (C) 2011
* @since 27
*/
@RunWith(Arquillian.class)
public class GreetingServiceTestCase {
@Deployment
public static Archive<?> deployment() {
return ShrinkWrap
.create(WebArchive.class, GreetingServiceTestCase.class.getSimpleName() + ".war")
.addPackage(CdiConfig.class.getPackage())
.setManifest(new StringAsset(Descriptors.create(ManifestDescriptor.class).attribute("Dependencies", "org.infinispan, org.infinispan.commons, org.infinispan.cdi.common meta-inf, org.infinispan.cdi.embedded meta-inf").exportAsString()))
.addAsWebInfResource(new StringAsset("<beans bean-discovery-mode=\"all\"></beans>"), "beans.xml")
;
}
@Inject
@GreetingCache
private org.infinispan.Cache<String, String> greetingCache;
@Inject
private GreetingService greetingService;
@Before
public void init() {
greetingCache.clear();
assertEquals(0, greetingCache.size());
}
@Test
public void testGreetMethod() {
assertEquals("Hello Pete :)", greetingService.greet("Pete"));
}
@Test
public void testGreetMethodCache() {
greetingService.greet("Pete");
assertEquals(1, greetingCache.size());
assertTrue(greetingCache.containsValue("Hello Pete :)"));
greetingService.greet("Manik");
assertEquals(2, greetingCache.size());
assertTrue(greetingCache.containsValue("Hello Manik :)"));
greetingService.greet("Pete");
assertEquals(2, greetingCache.size());
}
}
| 3,664
| 36.397959
| 250
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/infinispan/cdi/embedded/deployment/CdiConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 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.jboss.as.test.clustering.single.infinispan.cdi.embedded.deployment;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Disposes;
import jakarta.enterprise.inject.Produces;
import org.infinispan.cdi.embedded.ConfigureCache;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;
/**
* This is the CDI configuration class.
* <p>
* Adopted and adapted from Infinispan testsuite.
*
* @author Radoslav Husar
* @author Kevin Pollet <pollet.kevin@gmail.com> (C) 2011
* @author Galder Zamarreño
* @since 27
*/
public class CdiConfig {
/**
* <p>This producer defines the greeting cache configuration.</p>
*
* <p>This cache will have:
* <ul>
* <li>a maximum of 4 entries</li>
* <li>use the strategy LRU for eviction</li>
* </ul>
* </p>
*
* @return the greeting cache configuration.
*/
@GreetingCache
@ConfigureCache("greeting-cache")
@Produces
public Configuration greetingCache() {
return new ConfigurationBuilder().memory().storage(StorageType.HEAP).maxCount(128).build();
}
/**
* <p>This producer overrides the default cache configuration used by the default cache manager.</p>
*
* <p>The default cache configuration defines that a cache entry will have a lifespan of 60_000 ms.</p>
*/
@Produces
public Configuration defaultCacheConfiguration() {
return new ConfigurationBuilder()
.expiration().lifespan(60_000L)
.build();
}
@Produces
@ApplicationScoped
public EmbeddedCacheManager defaultEmbeddedCacheManager() {
return new DefaultCacheManager();
}
public void stopEmbeddedCacheManager(@Disposes EmbeddedCacheManager embeddedCacheManager) {
embeddedCacheManager.stop();
}
}
| 3,095
| 33.4
| 107
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/infinispan/cdi/embedded/deployment/GreetingService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 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.jboss.as.test.clustering.single.infinispan.cdi.embedded.deployment;
import jakarta.inject.Inject;
/**
* This is the Greeting Service class. Each call to the {@link GreetingService#greet(String)} method will be cached in the greeting-cache (in this case
* the CacheKey will be the name). If this method has been already called
* with the same name the cached value will be returned and this method will not be called.
* Adopted and adapted from Infinispan testsuite.
*
* @author Radoslav Husar
* @author Kevin Pollet <pollet.kevin@gmail.com> (C) 2011
* @since 27
*/
public class GreetingService {
@Inject
private GreetingCacheManager cacheManager;
// JCache: @CacheResult(cacheName = "greeting-cache")
public String greet(String name) {
String greeting = "Hello " + name + " :)";
cacheManager.cacheResult(name, greeting);
return greeting;
}
}
| 1,942
| 37.86
| 151
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/single/infinispan/cdi/embedded/deployment/GreetingCache.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 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.jboss.as.test.clustering.single.infinispan.cdi.embedded.deployment;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import jakarta.inject.Qualifier;
/**
* The greeting cache qualifier. This qualifier will be associated to the greeting cache in the {@link CdiConfig} class.
* Adopted and adapted from Infinispan testsuite.
*
* @author Radoslav Husar
* @author Kevin Pollet <pollet.kevin@gmail.com> (C) 2011
* @since 27
*/
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
@Documented
public @interface GreetingCache {
}
| 1,812
| 38.413043
| 120
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.