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/web/src/test/java/org/jboss/as/test/integration/web/handlestypes/HandlesTypesWarTestCase.java
|
package org.jboss.as.test.integration.web.handlestypes;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import jakarta.servlet.ServletContainerInitializer;
import java.util.Arrays;
import java.util.HashSet;
/**
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
public class HandlesTypesWarTestCase {
@Deployment
public static Archive<?> deploy() {
WebArchive war = ShrinkWrap.create(WebArchive.class)
.addClasses(SomeAnnotation.class)
.addClasses(AnnotatedParent.class, NonAnnotatedChild.class, AnnotatedChild.class)
.addClasses(HandlesTypesParent.class, HandlesTypesChild.class, HandlesTypesGandchild.class)
.addClasses(HandlesTypesInterface.class, HandlesTypesImplementor.class, HandlesTypesImplementorChild.class)
.addClasses(ParentServletContainerInitializer.class, ChildServletContainerInitializer.class, AnnotationServletContainerInitializer.class)
.addAsServiceProvider(ServletContainerInitializer.class, ParentServletContainerInitializer.class, ChildServletContainerInitializer.class, AnnotationServletContainerInitializer.class);
return war;
}
@Test
public void testParentClass() {
Class<?>[] expeccted = {HandlesTypesChild.class, HandlesTypesImplementor.class, HandlesTypesGandchild.class, HandlesTypesImplementorChild.class};
Assert.assertEquals(new HashSet<>(Arrays.asList(expeccted)), ParentServletContainerInitializer.HANDLES_TYPES);
}
@Test
public void testChildClass() {
Class<?>[] expeccted = {HandlesTypesGandchild.class, HandlesTypesImplementorChild.class};
Assert.assertEquals(new HashSet<>(Arrays.asList(expeccted)), ChildServletContainerInitializer.HANDLES_TYPES);
}
@Test
public void testAnnotatedClass() {
Class<?>[] expeccted = {AnnotatedParent.class, AnnotatedChild.class};
Assert.assertEquals(new HashSet<>(Arrays.asList(expeccted)), AnnotationServletContainerInitializer.HANDLES_TYPES);
}
}
| 2,312
| 44.352941
| 199
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlers/UndertowHandlersConfigTestCase.java
|
package org.jboss.as.test.integration.web.handlers;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.shared.integration.ejb.security.PermissionUtils;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.FilePermission;
import java.net.URL;
import static org.junit.Assert.assertEquals;
/**
* Tests the use of undertow-handlers.conf
*
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
@RunAsClient
public class UndertowHandlersConfigTestCase {
@Deployment
public static WebArchive deploy() {
return ShrinkWrap.create(WebArchive.class, "non-blocking-handler.war")
.addPackage(UndertowHandlersConfigTestCase.class.getPackage())
.addAsWebInfResource(UndertowHandlersConfigTestCase.class.getPackage(), "jboss-web.xml", "jboss-web.xml")
.addAsWebResource(new StringAsset("A file"), "file.txt")
.addAsWebInfResource(new StringAsset("regex['/rewrite.*'] -> rewrite['/file.txt']"), "undertow-handlers.conf")
.addAsWebResource(PermissionUtils.createPermissionsXmlAsset(new FilePermission("<<ALL FILES>>", "read,write")), "META-INF/permissions.xml");
}
@ArquillianResource
protected URL url;
@Test
public void testRewrite() throws Exception {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpget = new HttpGet(url.toExternalForm() + "rewritea");
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
assertEquals(200, statusLine.getStatusCode());
String result = EntityUtils.toString(entity);
Assert.assertEquals("A file", result);
Header[] headers = response.getHeaders("MyHeader");
Assert.assertEquals(1, headers.length);
Assert.assertEquals("MyValue", headers[0].getValue());
}
}
}
| 2,688
| 36.873239
| 156
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlers/SetHeaderHandler.java
|
package org.jboss.as.test.integration.web.handlers;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HttpString;
/**
* @author Stuart Douglas
*/
public class SetHeaderHandler implements HttpHandler {
private final HttpHandler next;
private String name;
private String value;
public SetHeaderHandler(HttpHandler next) {
this.next = next;
}
public void handleRequest(HttpServerExchange exchange) throws Exception {
exchange.getResponseHeaders().put(new HttpString(name), value);
next.handleRequest(exchange);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| 898
| 19.906977
| 77
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlers/RequestDumpingHandlerTestImpl.java
|
package org.jboss.as.test.integration.web.handlers;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import jakarta.websocket.ContainerProvider;
import jakarta.websocket.WebSocketContainer;
import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.util.EntityUtils;
import org.jboss.as.test.integration.web.websocket.AnnotatedClient;
import org.jboss.logging.Logger;
import org.junit.Assert;
/**
* Tests the use of Undertow request dumping handler. This is base class that implements particular test behaviour and controls
* what is tested.
*
* @author <a href="mailto:jstourac@redhat.com">Jan Stourac</a>
*/
public abstract class RequestDumpingHandlerTestImpl {
private static Logger log = Logger.getLogger(RequestDumpingHandlerTestImpl.class);
private final int TOTAL_DELAY = 3000;
private final int SLEEP_TIMEOUT = 200;
private final Path logFilePath;
// Expected value of the "contentType" header in response - default is "text/plain" but can be overridden by child class
protected String contentType = "text/plain";
// Expected value of the "status" header in response - default is "200" but can be overridden by child class
protected String status = "200";
// Expected value of the "scheme" header in request - default is "http" but can be overridden by child class
protected String scheme = "http";
/**
* Constructor that immediately executes test body.
*
* @param uri testing URI to connect to
* @param logFilePath path to log file in which are logged request dumps
* @param requestDumperOn whether request dumping feature is enabled at all
*/
public RequestDumpingHandlerTestImpl(URI uri, Path logFilePath, boolean requestDumperOn) throws Exception {
this.logFilePath = logFilePath;
commonTestBody(uri, requestDumperOn);
}
/***
* Abstract method which implements way of performing request to the server. It should be implemented depending on what type
* of request we want to perform (HTTP, HTTPS, etc.).
*
* @param uri testing URI to connect to
* @return 2dimensional array - request (as a first member) and response (as a second member) headers arrays; in case that
* there is no simple way how to obtain request and response headers then returns null
* @throws Exception
*/
public abstract Header[][] performRequest(URI uri) throws Exception;
/**
* Common test body part.
*
* @param uri deployment URI
* @param requestDumperOn whether RequestDumpingHandler is turned on
* @throws Exception
*/
private void commonTestBody(URI uri, boolean requestDumperOn) throws Exception {
// Test whether custom log file exists already. If so then count number of lines in it so further we will ignore them.
long skipBytes = 0;
if (logFilePath.toFile().exists() && logFilePath.toFile().isFile()) {
skipBytes = logFilePath.toFile().length();
} else {
log.trace("The log file ('" + logFilePath + "') does not exist yet, that is ok.");
}
// Perform request on server...
Header[] reqHdrs = null;
Header[] respHdrs = null;
Header[][] hdrs = performRequest(uri);
if (hdrs != null) {
reqHdrs = hdrs[0];
respHdrs = hdrs[1];
}
// Test whether there is request dump for particular URL after the HTTP request executed...
testLogForDumpWithURL(logFilePath, uri.getPath(), skipBytes, requestDumperOn);
if (requestDumperOn) {
// If we expect request dump -> check its data.
checkReqDumpData(logFilePath, skipBytes, reqHdrs, respHdrs, uri.getHost(), uri.getPort(), uri.getPath());
}
}
/**
* Reads content of the file into a string variable.
*
* @param logFilePath
* @param skipBytes number of bytes from the beginning of the file that should be skipped
* @return content of the file as a string
* @throws FileNotFoundException
*/
private String readLogFile(Path logFilePath, long skipBytes) throws FileNotFoundException, IOException {
Assert.assertTrue("Log file ('" + logFilePath + "') does not exist", logFilePath.toFile().exists());
Assert.assertTrue("The '" + logFilePath + "' is not a file", logFilePath.toFile().isFile());
// logfile exists -> read its content...
LineNumberReader lnr = new LineNumberReader(Files.newBufferedReader(logFilePath, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
log.trace("I am skipping '" + skipBytes + "' bytes from the beggining of the file.");
lnr.skip(skipBytes);
String input;
while ((input = lnr.readLine()) != null) {
sb.append("\n" + input);
}
lnr.close();
return sb.toString();
}
/**
* Searching log for request dump of request to particular path. If no such request dump is found there is sanity loop to
* ensure that system has had enough time to write data to the disk.
*
* @param logFilePath path to log file
* @param path URI path searched for in log file
* @param skipBytes number of bytes from the beginning of the file that should be skipped
* @param expected whether we expect to find given path
* @throws FileNotFoundException
*/
private void testLogForDumpWithURL(Path logFilePath, String path, long skipBytes, boolean expected) throws Exception {
Pattern pattern = Pattern.compile("-+REQUEST-+.+" + path + ".+-+RESPONSE-+", Pattern.DOTALL);
Matcher m;
long startTime = System.currentTimeMillis();
boolean hasFound = false;
long currTime;
String content;
// Give system time to write data on disk...
do {
currTime = System.currentTimeMillis();
content = readLogFile(logFilePath, skipBytes);
m = pattern.matcher(content);
// Search for pattern...
if (m.find()) {
hasFound = true;
break;
}
Thread.sleep(SLEEP_TIMEOUT);
} while (currTime - startTime < TOTAL_DELAY);
log.trace("I have read following content of the file '" + logFilePath + "':\n" + content + "\n---END-OF-FILE-OUTPUT---");
// Finally compare search result with our expectation...
Assert.assertEquals("Searching for pattern: '" + pattern + "' in log file ('" + logFilePath.toString() + "')",
expected, hasFound);
}
/**
* Check request dumper data.
*
* @param logFilePath path to log file
* @param skipBytes number of bytes from the beginning of the file that should be skipped
* @param reqHdrs request headers
* @param respHdrs response headers
* @param host server IP address
* @param port server listening port
* @param path URI path
* @throws IOException
*/
private void checkReqDumpData(Path logFilePath, long skipBytes, Header[] reqHdrs, Header[] respHdrs, String host, int port, String path) throws IOException {
String content = readLogFile(logFilePath, skipBytes);
// Split into request and response part:
String request = content.substring(0, content.indexOf("-RESPONSE-"));
String response = content.substring(content.indexOf("-RESPONSE-"));
// Check request dump part...
searchInFile(request, "-+REQUEST-+");
searchInFile(request, "\\s+URI=" + Pattern.quote(path));
searchInFile(request, "\\s+characterEncoding=");
searchInFile(request, "\\s+contentLength=");
searchInFile(request, "\\s+contentType=");
searchForHeaders(request, reqHdrs);
searchInFile(request, "\\s+locale=\\[.*\\]");
searchInFile(request, "\\s+method=GET");
searchInFile(request, "\\s+protocol=");
searchInFile(request, "\\s+queryString=");
searchInFile(request, "\\s+remoteAddr=");
searchInFile(request, "\\s+remoteHost=");
searchInFile(request, "\\s+scheme=" + Pattern.quote(scheme));
searchInFile(request, "\\s+host=" + Pattern.quote(host));
searchInFile(request, "\\s+serverPort=" + Pattern.quote(String.valueOf(port)));
// Now check response dump part...
searchInFile(response, "-+RESPONSE-+");
searchInFile(response, "\\s+contentLength=");
searchInFile(response, "\\s+contentType=" + Pattern.quote(contentType));
searchForHeaders(response, respHdrs);
searchInFile(response, "\\s+status=" + Pattern.quote(status));
}
/**
* Search for request and response headers. Respect that they might be in different order.
*
* @param content content in which is searched
* @param hdrs array of headers which should be searched for; if null then no check will be performed; if zero length then
* no header line is expected in the log
* @throws FileNotFoundException
*/
private void searchForHeaders(String content, Header[] hdrs) throws FileNotFoundException {
if (hdrs == null) {
log.trace("No array with headers given -> skipping testing header content in log file.");
return;
}
final String HEADER_REGEXP = "\\s+header=";
if (hdrs.length > 0) {
// Check that number of "header" occurrences equals to hdrs.length
Assert.assertEquals("", hdrs.length, countMatch(content, HEADER_REGEXP));
for (Header hdr : hdrs) {
// Close current scanner, reopen it and move to start pattern directly...
searchInFile(content, HEADER_REGEXP + Pattern.quote(hdr.getName()) + "=" + Pattern.quote(hdr.getValue()));
}
} else {
// request contains no headers -> we really do not expect it to be in dump
searchInFile(content, HEADER_REGEXP, false);
}
}
/**
* Searches in given content for given pattern.
*
* @param content content of the file as a string
* @param regExp regular expression that is searched in the file
*/
private void searchInFile(String content, String regExp) {
searchInFile(content, regExp, true);
}
/**
* Searches in given content for given pattern.
*
* @param content content of the file as a string
* @param regExp regular expression that is searched in the file
* @param expected whether searching pattern is expected to be found or not
*/
private void searchInFile(String content, String regExp, boolean expected) {
Pattern pattern = Pattern.compile(regExp);
Matcher m = pattern.matcher(content);
Assert.assertEquals("Searching for pattern: '" + regExp + "' in log file ('" + logFilePath.toString() + "')", expected,
m.find());
}
/**
* Counts number of occurrences of given string in given content.
*
* @param content in this content will be searching for given pattern
* @param regExp given pattern to search in content
* @return number of occurrences in given content
*/
private int countMatch(String content, String regExp) {
Pattern pattern = Pattern.compile(regExp);
Matcher m = pattern.matcher(content);
int occurs = 0;
while (m.find()) {
occurs++;
}
return occurs;
}
/**
* Testing class which implements HTTPS requests on server.
*
* @author <a href="mailto:jstourac@redhat.com">Jan Stourac</a>
*/
static class HttpsRequestDumpingHandlerTestImpl extends RequestDumpingHandlerTestImpl {
HttpsRequestDumpingHandlerTestImpl(URI uri, Path logFilePath, boolean requestDumperOn) throws Exception {
super(uri, logFilePath, requestDumperOn);
}
@Override
public Header[][] performRequest(URI uri) throws Exception {
// Override value of the "scheme" header expected in response
scheme = "https";
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}};
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection httpsConn = (HttpsURLConnection) uri.toURL().openConnection();
httpsConn.setDoOutput(false);
httpsConn.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
BufferedReader br = new BufferedReader(new InputStreamReader(httpsConn.getInputStream(), StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
String input;
while ((input = br.readLine()) != null) {
sb = sb.append(input);
}
br.close();
httpsConn.disconnect();
Header[][] reqAndrespHeaders = new Header[2][];
reqAndrespHeaders[1] = retrieveHeaders(httpsConn.getHeaderFields());
log.trace("The content of the URL ('" + uri + "'):\n" + sb.toString());
Assert.assertEquals(200, httpsConn.getResponseCode());
Assert.assertEquals("Could not reach expected content via http request", "A file", sb.toString());
// NOTE: leaving request headers null (won't be checked) as there is no easy way how to obtain them
return reqAndrespHeaders;
}
private Header[] retrieveHeaders(Map<String, List<String>> headers) {
//System.out.println("---- PRINTING HEADERS ----");
LinkedList<Header> hdrsList = new LinkedList<Header>();
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
for (String value : entry.getValue()) {
if (entry.getKey() != null) {
//System.out.println(header + ": " + value);
hdrsList.add(new BasicHeader(entry.getKey(), value));
}
}
}
return hdrsList.toArray(new Header[hdrsList.size()]);
}
}
/**
* Testing class that implements standard HTTP requests.
*
* @author <a href="mailto:jstourac@redhat.com">Jan Stourac</a>
*/
static class HttpRequestDumpingHandlerTestImpl extends RequestDumpingHandlerTestImpl {
HttpRequestDumpingHandlerTestImpl(URI uri, Path logFilePath, boolean requestDumperOn) throws Exception {
super(uri, logFilePath, requestDumperOn);
}
@Override
public Header[][] performRequest(URI uri) throws Exception {
Header[][] ret = new Header[2][];
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpGet httpget = new HttpGet(uri.toURL().toExternalForm() + "file.txt");
HttpContext localContext = new BasicHttpContext();
HttpResponse response = httpClient.execute(httpget, localContext);
HttpRequest request = (HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
// Fill return values
ret[0] = request.getAllHeaders();
ret[1] = response.getAllHeaders();
StatusLine statusLine = response.getStatusLine();
Assert.assertEquals(200, statusLine.getStatusCode());
String result = EntityUtils.toString(response.getEntity());
Assert.assertEquals("Could not reach expected content via http request", "A file", result);
}
return ret;
}
}
/**
* Testing class that implements standard websocket requests via http upgrade.
*
* @author <a href="mailto:jstourac@redhat.com">Jan Stourac</a>
*/
static class WsRequestDumpingHandlerTestImpl extends RequestDumpingHandlerTestImpl {
WsRequestDumpingHandlerTestImpl(URI uri, Path logFilePath, boolean requestDumperOn) throws Exception {
super(uri, logFilePath, requestDumperOn);
}
@Override
public Header[][] performRequest(URI uri) throws Exception {
// Override value of the "contentType" header expected in response
contentType = "null";
// Override value of the "status" header expected in response
status = "101";
AnnotatedClient endpoint = new AnnotatedClient();
WebSocketContainer serverContainer = ContainerProvider.getWebSocketContainer();
serverContainer.connectToServer(endpoint, uri);
Assert.assertEquals("Hello Stuart", endpoint.getMessage());
// NOTE: leaving request and response headers null (won't be checked) as there is no easy way how to obtain them
return null;
}
}
}
| 18,911
| 39.846652
| 161
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlers/RequestDumpingHandlerTestCase.java
|
package org.jboss.as.test.integration.web.handlers;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FILE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FILE_HANDLER;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.LOGGER;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PERIODIC_ROTATING_FILE_HANDLER;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROTOCOL;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.io.File;
import java.net.SocketPermission;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.PropertyPermission;
import org.apache.commons.io.FileUtils;
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.controller.PathAddress;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.management.ManagementOperations;
import org.jboss.as.test.integration.security.common.SecurityTestConstants;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.integration.web.websocket.WebSocketTestCase;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.as.test.shared.SnapshotRestoreSetupTask;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests the use of undertow request dumping handler.
*
* @author <a href="mailto:jstourac@redhat.com">Jan Stourac</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(RequestDumpingHandlerTestCase.RequestDumpingHandlerTestCaseSetupAction.class)
public class RequestDumpingHandlerTestCase {
public static class RequestDumpingHandlerTestCaseSetupAction extends SnapshotRestoreSetupTask {
private static String relativeTo;
private static ModelNode originalValue;
/** Name of the log file that will be used for testing. */
private static final String LOG_FILE_PREFIX = "test_server_" + System.currentTimeMillis();
private static final String LOG_FILE_SUFFIX = ".log";
// Address to server log setting
private static final PathAddress aLogAddr = PathAddress.pathAddress().append(SUBSYSTEM, "logging")
.append(PERIODIC_ROTATING_FILE_HANDLER, "FILE");
// Address to custom file handler
private static final String FILE_HANDLER_NAME = "testing-req-dump-handler";
private static final PathAddress ADDR_FILE_HANDLER = PathAddress.pathAddress().append(SUBSYSTEM, "logging")
.append(FILE_HANDLER, FILE_HANDLER_NAME);
// Address to custom logger
private static final String LOGGER_NAME = "io.undertow.request.dump";
private static final PathAddress ADDR_LOGGER = PathAddress.pathAddress().append(SUBSYSTEM, "logging")
.append(LOGGER, LOGGER_NAME);
private static final File WORK_DIR = new File("https-workdir");
public static final File SERVER_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.SERVER_KEYSTORE);
public static final File SERVER_TRUSTSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.SERVER_TRUSTSTORE);
public static final File CLIENT_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.CLIENT_KEYSTORE);
public static final File CLIENT_TRUSTSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.CLIENT_TRUSTSTORE);
public static final File UNTRUSTED_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.UNTRUSTED_KEYSTORE);
private static final String HTTPS = "https";
private static final String HTTPS_LISTENER_PATH = "subsystem=undertow/server=default-server/https-listener=" + HTTPS;
private static final String HTTPS_REALM = "httpsRealm";
private static final String HTTPS_REALM_PATH = "core-service=management/security-realm=" + HTTPS_REALM;
private static final String HTTPS_REALM_AUTH_PATH = HTTPS_REALM_PATH + "/authentication=truststore";
private static final String HTTPS_REALM_SSL_PATH = HTTPS_REALM_PATH + "/server-identity=ssl";
@Override
public void doSetup(ManagementClient managementClient, String containerId) throws Exception {
// Retrieve original path to server log files
ModelNode op = Util.getReadAttributeOperation(aLogAddr, "file");
originalValue = ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
log.debug("Original value: " + originalValue.toString());
// Retrieve relative path to log files
relativeTo = originalValue.get("relative-to").asString();
op = Util.getReadAttributeOperation(PathAddress.pathAddress("path", relativeTo), "path");
ModelNode logPathModel = ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
logFilePath = Paths.get(logPathModel.asString() + File.separator + LOG_FILE_PREFIX + LOG_FILE_SUFFIX);
// Set custom file handler to log dumping requests into separate log file
ModelNode file = new ModelNode();
file.get("relative-to").set(relativeTo);
file.get("path").set(LOG_FILE_PREFIX + LOG_FILE_SUFFIX);
op = Util.createAddOperation(ADDR_FILE_HANDLER);
op.get(FILE).set(file);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
// Set custom logger that uses previous custom file handler for logging
op = Util.createAddOperation(ADDR_LOGGER);
LinkedList<ModelNode> handlers = new LinkedList<ModelNode>();
handlers.add(new ModelNode(FILE_HANDLER_NAME));
op.get("handlers").set(handlers);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
// Set HTTPS listener...
FileUtils.deleteDirectory(WORK_DIR);
WORK_DIR.mkdirs();
Utils.createKeyMaterial(WORK_DIR);
// add new HTTPS_REALM with SSL
ModelNode operation = createOpNode(HTTPS_REALM_PATH, ModelDescriptionConstants.ADD);
Utils.applyUpdate(operation, managementClient.getControllerClient());
operation = createOpNode(HTTPS_REALM_AUTH_PATH, ModelDescriptionConstants.ADD);
operation.get("keystore-path").set(SERVER_TRUSTSTORE_FILE.getAbsolutePath());
operation.get("keystore-password").set(SecurityTestConstants.KEYSTORE_PASSWORD);
Utils.applyUpdate(operation, managementClient.getControllerClient());
operation = createOpNode(HTTPS_REALM_SSL_PATH, ModelDescriptionConstants.ADD);
operation.get(PROTOCOL).set("TLSv1");
operation.get("keystore-path").set(SERVER_KEYSTORE_FILE.getAbsolutePath());
operation.get("keystore-password").set(SecurityTestConstants.KEYSTORE_PASSWORD);
Utils.applyUpdate(operation, managementClient.getControllerClient());
operation = createOpNode(HTTPS_LISTENER_PATH, ModelDescriptionConstants.ADD);
operation.get("socket-binding").set(HTTPS);
operation.get("security-realm").set(HTTPS_REALM);
Utils.applyUpdate(operation, managementClient.getControllerClient());
ServerReload.executeReloadAndWaitForCompletion(managementClient);
}
@Override
protected void nonManagementCleanUp() throws Exception {
// Delete custom server log file
Files.delete(logFilePath);
// Delete folder with HTTPS files
FileUtils.deleteDirectory(WORK_DIR);
}
}
private static Logger log = Logger.getLogger(RequestDumpingHandlerTestCase.class);
/** Path to custom server log file. */
private static Path logFilePath;
private final String HTTPS_PORT = "8443";
private static final String DEPLOYMENT = "no-req-dump";
private static final String DEPLOYMENT_DUMP = "req-dump";
private static final String DEPLOYMENT_WS = "req-dump-ws";
@Deployment(name = DEPLOYMENT_DUMP)
public static WebArchive deployWithReqDump() {
WebArchive war = ShrinkWrap
.create(WebArchive.class, DEPLOYMENT_DUMP + ".war")
.addPackage(RequestDumpingHandlerTestCase.class.getPackage())
.addAsWebInfResource(RequestDumpingHandlerTestCase.class.getPackage(), "jboss-web-req-dump.xml",
"jboss-web.xml").addAsWebResource(new StringAsset("A file"), "file.txt");
return war;
}
@Deployment(name = DEPLOYMENT)
public static WebArchive deployWithoutReqDump() {
WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT + ".war")
.addPackage(RequestDumpingHandlerTestCase.class.getPackage())
.addAsWebInfResource(RequestDumpingHandlerTestCase.class.getPackage(), "jboss-web.xml", "jboss-web.xml")
.addAsWebResource(new StringAsset("A file"), "file.txt");
return war;
}
@Deployment(name = DEPLOYMENT_WS)
public static WebArchive deploy() {
WebArchive war = ShrinkWrap
.create(WebArchive.class, DEPLOYMENT_WS + ".war")
.addPackage(WebSocketTestCase.class.getPackage())
.addClass(TestSuiteEnvironment.class)
.addAsManifestResource(createPermissionsXmlAsset(
// Needed for the TestSuiteEnvironment.getServerAddress()
new PropertyPermission("management.address", "read"),
new PropertyPermission("node0", "read"),
new PropertyPermission("jboss.http.port", "read"),
// Needed for the serverContainer.connectToServer()
new SocketPermission("*:" + TestSuiteEnvironment.getHttpPort(), "connect,resolve")), "permissions.xml")
.addAsManifestResource(new StringAsset("io.undertow.websockets.jsr.UndertowContainerProvider"),
"services/jakarta.websocket.ContainerProvider")
.addAsWebInfResource(RequestDumpingHandlerTestCase.class.getPackage(), "jboss-web-req-dump.xml",
"jboss-web.xml");
return war;
}
/**
* Testing app has already defined request dumper handler. This test checks that when a request to URL is performed then
* request detail data is stored in proper format in the proper log file.
*/
@Test
@OperateOnDeployment(DEPLOYMENT_DUMP)
public void testReqDumpHandlerOn(@ArquillianResource URL url) throws Exception {
new RequestDumpingHandlerTestImpl.HttpRequestDumpingHandlerTestImpl(url.toURI(), logFilePath, true);
}
/**
* Testing app has no request dumper handler registered. This test checks that there is not dumped additional info about
* executed request in the log file.
*/
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testReqDumpHandlerOff(@ArquillianResource URL url) throws Exception {
new RequestDumpingHandlerTestImpl.HttpRequestDumpingHandlerTestImpl(url.toURI(), logFilePath, false);
}
/**
* Testing app has request dumper handler registered. This test checks that request dump over the HTTPS is generated
* correctly.
*/
@Test
@OperateOnDeployment(DEPLOYMENT_DUMP)
public void testReqDumpHandlerOnHttps(@ArquillianResource URL url) throws Exception {
URL httpsUrl = new URL("https://" + url.getHost() + ":" + HTTPS_PORT + url.getPath() + "file.txt");
new RequestDumpingHandlerTestImpl.HttpsRequestDumpingHandlerTestImpl(httpsUrl.toURI(), logFilePath, true);
}
/**
* Testing app has request dumper handler registered. This test checks that request dump over the Websockets is generated
* correctly.
*/
@Test
@OperateOnDeployment(DEPLOYMENT_WS)
public void testReqDumpHandlerOnWebsockets(@ArquillianResource URL url) throws Exception {
URI wsUri = new URI("ws", "", TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getHttpPort(), "/" + DEPLOYMENT_WS + "/websocket/Stuart",
"", "");
new RequestDumpingHandlerTestImpl.WsRequestDumpingHandlerTestImpl(wsUri, logFilePath, true);
}
}
| 13,303
| 51.172549
| 157
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlers/ForwardedTestHelperServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.handlers;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jboss.as.test.shared.TestSuiteEnvironment;
/**
* @author Jan Stourac
*/
@WebServlet(name = "ForwardedHelperServlet", urlPatterns = {"/forwarded"})
public class ForwardedTestHelperServlet extends HttpServlet {
private String message;
@Override
public void init(ServletConfig config) throws ServletException {
message = config.getInitParameter("message");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
String localAddr = req.getLocalAddr();
if(localAddr.startsWith("/")) {
localAddr = "/" + TestSuiteEnvironment.formatPossibleIpv6Address(localAddr.substring(1));
} else {
localAddr = TestSuiteEnvironment.formatPossibleIpv6Address(localAddr);
}
out.print(req.getRemoteAddr() + "|" + req.getRemoteHost() + ":" + req.getRemotePort() + "|" + req.getScheme()
+ "|" + req.getLocalName() + "|" + localAddr + ":" + req.getLocalPort());
out.close();
}
}
| 2,507
| 38.1875
| 117
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlers/SameSiteCookieHandlerTestCase.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.integration.web.handlers;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
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.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import io.undertow.server.handlers.CookieSameSiteMode;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
/**
* Tests the use of SameSiteCookieHandler
*
* @author Flavia Rainone
*/
@RunWith(Arquillian.class)
@RunAsClient
public class SameSiteCookieHandlerTestCase {
// war file names
private static final String PLAIN_WEB_APP = "cookie-servlet.war";
private static final String LAX_SAMESITE_COOKIE_WEB_APP = "lax-samesite-cookie-servlet.war";
private static final String STRICT_SAMESITE_COOKIE_WEB_APP = "strict-samesite-cookie-servlet.war";
private static final String NONE_SAMESITE_COOKIE_WEB_APP = "none-samesite-cookie-servlet.war";
private static final String NONE_SAMESITE_UNSECURE_COOKIE_WEB_APP = "none-samesite-unsecure-cookie-servlet.war";
// handler config
private static final String SAMESITE_COOKIE_HANDLER_NAME = "samesite-cookie";
private static final String SAMESITE_COOKIE_LAX_HANDLER = SAMESITE_COOKIE_HANDLER_NAME
+ "(" + CookieSameSiteMode.LAX + ")";
private static final String SAMESITE_COOKIE_STRICT_HANDLER = SAMESITE_COOKIE_HANDLER_NAME
+ "(" + CookieSameSiteMode.STRICT + ")";
private static final String SAMESITE_COOKIE_NONE_HANDLER = SAMESITE_COOKIE_HANDLER_NAME
+ "(" + CookieSameSiteMode.NONE + ")";
private static final String SAMESITE_COOKIE_NONE_HANDLER_UNSECURE = SAMESITE_COOKIE_HANDLER_NAME
+ "(mode=" + CookieSameSiteMode.NONE + ",add-secure-for-none=false)";
@WebServlet(name = "CookieServlet", urlPatterns = {"/cookieservlet"})
public static class CookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
PrintWriter out = resp.getWriter();
resp.addCookie(new Cookie("cookie", "created-by-servlet"));
out.print("hello world");
out.close();
}
}
@Deployment(name = PLAIN_WEB_APP)
public static WebArchive deploy_plain_war() {
return ShrinkWrap.create(WebArchive.class, PLAIN_WEB_APP)
.addClass(CookieServlet.class);
}
@Deployment(name = LAX_SAMESITE_COOKIE_WEB_APP)
public static WebArchive deploy_war_with_samesite_lax() {
return ShrinkWrap.create(WebArchive.class, LAX_SAMESITE_COOKIE_WEB_APP)
.addClass(CookieServlet.class)
.addAsWebInfResource(new StringAsset(
SAMESITE_COOKIE_LAX_HANDLER), "undertow-handlers.conf");
}
@Deployment(name = STRICT_SAMESITE_COOKIE_WEB_APP)
public static WebArchive deploy_war_with_samesite_strict() {
return ShrinkWrap.create(WebArchive.class,
STRICT_SAMESITE_COOKIE_WEB_APP)
.addClass(CookieServlet.class)
.addAsWebInfResource(new StringAsset(
SAMESITE_COOKIE_STRICT_HANDLER), "undertow-handlers.conf");
}
@Deployment(name = NONE_SAMESITE_COOKIE_WEB_APP)
public static WebArchive deploy_war_with_samesite_none() {
return ShrinkWrap.create(WebArchive.class, NONE_SAMESITE_COOKIE_WEB_APP)
.addClass(CookieServlet.class)
.addAsWebInfResource(new StringAsset(
SAMESITE_COOKIE_NONE_HANDLER), "undertow-handlers.conf");
}
@Deployment(name = NONE_SAMESITE_UNSECURE_COOKIE_WEB_APP)
public static WebArchive deploy_war_with_samesite_none_unsecure() {
return ShrinkWrap.create(WebArchive.class,
NONE_SAMESITE_UNSECURE_COOKIE_WEB_APP)
.addClass(CookieServlet.class)
.addAsWebInfResource(new StringAsset(
SAMESITE_COOKIE_NONE_HANDLER_UNSECURE), "undertow-handlers.conf");
}
@Test
@OperateOnDeployment(PLAIN_WEB_APP)
public void testWebAppWithoutHandler(@ArquillianResource URL url) throws Exception {
commonTestPart(new URL(url + "/cookieservlet"), null, false);
}
@Test
@OperateOnDeployment(LAX_SAMESITE_COOKIE_WEB_APP)
public void testWebAppWithLaxSameSiteCookieHandler(@ArquillianResource URL url) throws Exception {
commonTestPart(new URL(url + "/cookieservlet"), CookieSameSiteMode.LAX, false);
}
@Test
@OperateOnDeployment(STRICT_SAMESITE_COOKIE_WEB_APP)
public void testWebAppWithStrictSameSiteCookieHandler(@ArquillianResource URL url) throws Exception {
commonTestPart(new URL(url + "/cookieservlet"), CookieSameSiteMode.STRICT, false);
}
@Test
@OperateOnDeployment(NONE_SAMESITE_COOKIE_WEB_APP)
public void testWebAppWithNoneSameSiteCookieHandler(@ArquillianResource URL url) throws Exception {
commonTestPart(new URL(url + "/cookieservlet"), CookieSameSiteMode.NONE, true);
}
@Test
@OperateOnDeployment(NONE_SAMESITE_UNSECURE_COOKIE_WEB_APP)
public void testWebAppWithNoneSameSiteUnsecureCookieHandler(@ArquillianResource URL url) throws Exception {
commonTestPart(new URL(url + "/cookieservlet"), CookieSameSiteMode.NONE, false);
}
private void commonTestPart(URL url, CookieSameSiteMode mode, boolean secure) throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpget = new HttpGet(url.toExternalForm());
HttpResponse response = httpClient.execute(httpget);
StatusLine statusLine = response.getStatusLine();
assertEquals(200, statusLine.getStatusCode());
Header[] hdrs = response.getHeaders("set-cookie");
Assert.assertEquals(1, hdrs.length);
if (secure) {
String cookieValue = hdrs[0].getValue();
Assert.assertEquals("cookie=created-by-servlet; secure; SameSite=" + mode, cookieValue);
} else {
String expectedCookie = "cookie=created-by-servlet" + (mode == null? "" :"; SameSite=" + mode);
Assert.assertEquals(expectedCookie, hdrs[0].getValue());
}
}
}
}
| 8,264
| 42.962766
| 116
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlers/ForwardedHandlerTestCase.java
|
package org.jboss.as.test.integration.web.handlers;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALLOW_RESOURCE_SERVICE_RESTART;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketPermission;
import java.net.URL;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ContainerResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.management.ManagementOperations;
import org.jboss.as.test.integration.management.util.MgmtOperationException;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests the use of undertow-handlers.conf
*
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
@RunAsClient
public class ForwardedHandlerTestCase {
private static final String FORWARDED_HANDLER_NO_UT_HANDLERS = "forwarded-handler-no-ut-handlers";
private static final String FORWARDED_SERVLET = "forwarded-servlet";
private static final String FORWARDED_SERVLET_NO_UT_HANDLERS = "forwarded-servlet-no-ut-handlers";
private static final String FORWARDER_HANDLER_NAME = "forwarded";
private static final PathAddress FORWARDER_CONF_ADDR = PathAddress.pathAddress().append(SUBSYSTEM, "undertow")
.append("configuration", "filter").append("expression-filter", "ff");
private static final PathAddress FORWARDER_FILTER_REF_ADDR = PathAddress.pathAddress().append(SUBSYSTEM, "undertow")
.append("server", "default-server").append("host", "default-host").append("filter-ref", "ff");
private static final String JBOSS_WEB_TEXT = "<?xml version=\"1.0\"?>\n" +
"<jboss-web>\n" +
" <http-handler>\n" +
" <class-name>org.jboss.as.test.integration.web.handlers.ForwardedTestHelperHandler</class-name>\n" +
" </http-handler>\n" +
"</jboss-web>";
@ContainerResource
private ManagementClient managementClient;
@Deployment(name = FORWARDED_HANDLER_NO_UT_HANDLERS)
public static WebArchive deployWithoutUndertowHandlers() {
return ShrinkWrap.create(WebArchive.class, FORWARDED_HANDLER_NO_UT_HANDLERS + ".war")
.addPackage(ForwardedHandlerTestCase.class.getPackage())
.addClass(TestSuiteEnvironment.class)
.addAsWebInfResource(new StringAsset(JBOSS_WEB_TEXT), "jboss-web.xml")
.addAsWebResource(new StringAsset("A file"), "index.html")
.addAsManifestResource(
createPermissionsXmlAsset(
new SocketPermission("*:0", "listen,resolve")),
"permissions.xml");
}
@Deployment(name = FORWARDED_SERVLET)
public static WebArchive deploy_servlet() {
return ShrinkWrap.create(WebArchive.class, FORWARDED_SERVLET + ".war")
.addClass(ForwardedTestHelperServlet.class)
.addClass(TestSuiteEnvironment.class)
.addAsWebInfResource(new StringAsset(FORWARDER_HANDLER_NAME), "undertow-handlers.conf")
.addAsWebResource(new StringAsset("A file"), "index.html");
}
@Deployment(name = FORWARDED_SERVLET_NO_UT_HANDLERS)
public static WebArchive deployWithoutUndertowHandlers_servlet() {
return ShrinkWrap.create(WebArchive.class, FORWARDED_SERVLET_NO_UT_HANDLERS + ".war")
.addClass(ForwardedTestHelperServlet.class)
.addClass(TestSuiteEnvironment.class)
.addAsWebResource(new StringAsset("A file"), "index.html");
}
@Test
@OperateOnDeployment(FORWARDED_HANDLER_NO_UT_HANDLERS)
public void testRewriteGlobalSettings(@ArquillianResource URL url) throws Exception {
commonConfigureExpression(url, true);
}
@Test
@OperateOnDeployment(FORWARDED_SERVLET)
public void testRewriteWithUndertowHandlersServlet(@ArquillianResource URL url) throws Exception {
commonTestPart(new URL(url + "/forwarded"), false);
}
@Test
@OperateOnDeployment(FORWARDED_SERVLET_NO_UT_HANDLERS)
public void testRewriteGlobalSettingsServlet(@ArquillianResource URL url) throws Exception {
commonConfigureExpression(new URL(url + "/forwarded"), false);
}
private void commonConfigureExpression(URL url, boolean header) throws IOException, MgmtOperationException {
ModelNode op = Util.createAddOperation(FORWARDER_CONF_ADDR);
op.get("expression").set(FORWARDER_HANDLER_NAME);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
op = Util.createAddOperation(FORWARDER_FILTER_REF_ADDR);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
try {
commonTestPart(url, header);
} finally {
op = Util.createRemoveOperation(FORWARDER_FILTER_REF_ADDR);
op.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
op = Util.createRemoveOperation(FORWARDER_CONF_ADDR);
op.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true);
ManagementOperations.executeOperation(managementClient.getControllerClient(), op);
}
}
private void commonTestPart(URL url, boolean header) throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
final String proto = "https";
final String forAddrOnly = "192.121.210.60";
final String forAddr = forAddrOnly + ":455";
final String by = "203.0.113.43:777";
final InetAddress addr = InetAddress.getByName(url.getHost());
final String localAddrName = addr.getHostName();
final String localAddr = TestSuiteEnvironment.formatPossibleIpv6Address(addr.getHostAddress()) + ":" + url.getPort();
HttpGet httpget = new HttpGet(url.toExternalForm());
httpget.addHeader("Forwarded", "for=" + forAddr + ";proto=" + proto + ";by=" + by);
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
assertEquals(200, statusLine.getStatusCode());
if (header) {
Header[] hdrs = response.getHeaders(ForwardedTestHelperHandler.FORWARD_TEST_HEADER);
Assert.assertEquals(1, hdrs.length);
Assert.assertEquals("/" + forAddr + "|" + proto + "|" + "/" + localAddr, hdrs[0].getValue());
} else {
String result = EntityUtils.toString(entity);
Assert.assertEquals(forAddrOnly + "|" + forAddr + "|" + proto + "|" + localAddrName + "|" + localAddr, result);
}
}
}
}
| 8,158
| 47.278107
| 129
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/handlers/ForwardedTestHelperHandler.java
|
package org.jboss.as.test.integration.web.handlers;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HttpString;
import org.jboss.as.test.shared.TestSuiteEnvironment;
/**
* @author Jan Stourac
*/
public class ForwardedTestHelperHandler implements HttpHandler {
public static final String FORWARD_TEST_HEADER = "forwarded-test-header";
private final HttpHandler next;
public ForwardedTestHelperHandler(HttpHandler next) {
this.next = next;
}
public void handleRequest(HttpServerExchange exchange) throws Exception {
String address = exchange.getDestinationAddress().getAddress().toString();
if(address.startsWith("/")) {
address = "/" + TestSuiteEnvironment.formatPossibleIpv6Address(address.substring(1));
} else {
address = TestSuiteEnvironment.formatPossibleIpv6Address(address);
}
String value = exchange.getSourceAddress() + "|" + exchange.getRequestScheme() + "|"
+ address + ':' + exchange.getDestinationAddress().getPort();
exchange.getResponseHeaders().put(new HttpString(FORWARD_TEST_HEADER), value);
next.handleRequest(exchange);
}
}
| 1,243
| 32.621622
| 97
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/jsp/JspMappingTestCase.java
|
/*
* Copyright (C) 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 library 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 library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.jboss.as.test.integration.web.jsp;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.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.Test;
import org.junit.runner.RunWith;
/**
* Test case for Jakarta Server Pages pattern declaration in web.xml
*
* @author <a href="mailto:ehugonne@redhat.com">Emmanuel Hugonnet</a> (c) 2014
* Red Hat, inc.
*/
@RunWith(Arquillian.class)
@RunAsClient
public class JspMappingTestCase {
protected static Logger log = Logger.getLogger(JspMappingTestCase.class);
@ArquillianResource
protected URL webappUrl;
private static final String JSP_CONTENT = "<%@page contentType=\"text/html\" pageEncoding=\"UTF-8\"%>\n"
+ "<!DOCTYPE html>\n"
+ "<html>\n"
+ " <body>\n"
+ " <p>\n"
+ " Hello. Because of the mapping in web.xml, I should be evaluated as a JSP:\n"
+ " </p>\n"
+ " <p>\n"
+ " 1 + 1 = ${1+1}\n"
+ " </p>\n"
+ " </body>\n"
+ "</html>";
@Deployment
public static WebArchive deployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "jbosstest-jsp.war");
war.addAsWebResource(new StringAsset(JSP_CONTENT), "test.html");
war.addAsWebResource(new StringAsset(JSP_CONTENT), "index.html");
war.addAsWebResource(new StringAsset(JSP_CONTENT), "index.jsp");
war.addAsWebResource(new StringAsset(JSP_CONTENT), "test.css");
war.addAsWebInfResource(JspMappingTestCase.class.getPackage(), "web.xml", "web.xml");
return war;
}
@Test
public void testSimpleJSP() throws Exception {
log.trace("Simple JSP");
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpResponse response = httpClient.execute(new HttpGet(webappUrl.toURI() + "index.jsp"));
try (InputStream in = response.getEntity().getContent()) {
String content = getContent(in);
assertThat(content, containsString("1 + 1 = 2"));
}
}
}
@Test
public void testFalseCss() throws Exception {
log.trace("False CSS");
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpResponse response = httpClient.execute(new HttpGet(webappUrl.toURI() + "test.css"));
try (InputStream in = response.getEntity().getContent()) {
String content = getContent(in);
assertThat(content, containsString("1 + 1 = 2"));
}
}
}
@Test
public void testFalseHtmlPage() throws Exception {
log.trace("False HTML");
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpResponse response = httpClient.execute(new HttpGet(webappUrl.toURI() + "test.html"));
try (InputStream in = response.getEntity().getContent()) {
String content = getContent(in);
assertThat(content, containsString("1 + 1 = 2"));
}
}
}
@Test
public void testTrueHtmlPage() throws Exception {
log.trace("True HTML");
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpResponse response = httpClient.execute(new HttpGet(webappUrl.toURI() + "index.html"));
try (InputStream in = response.getEntity().getContent()) {
String content = getContent(in);
assertThat(content, not(containsString("1 + 1 = 2")));
}
}
}
private String getContent(InputStream content) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(content, StandardCharsets.UTF_8));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
return out.toString();
}
}
| 5,770
| 38.527397
| 108
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/jsp/JspSecurityManagerTestCase.java
|
package org.jboss.as.test.integration.web.jsp;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.net.URL;
import java.util.concurrent.TimeUnit;
@RunWith(Arquillian.class)
@RunAsClient
public class JspSecurityManagerTestCase {
private static final StringAsset WEB_XML = new StringAsset(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<web-app xmlns=\"http://java.sun.com/xml/ns/javaee\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd\"\n" +
" version=\"3.1\">\n" +
"</web-app>");
private static final StringAsset INDEX_JSP = new StringAsset(
"<%@ page contentType=\"text/html;charset=UTF-8\" language=\"java\" %>\n" +
"<html>\n" +
" <head>\n" +
" <title></title>\n" +
" </head>\n" +
" <body>\n" +
"<%= System.getProperty(\"java.home\") %>" +
" </body>\n" +
"</html>");
@Deployment
public static WebArchive deploy() {
return ShrinkWrap.create(WebArchive.class, "read-props.war")
.addAsWebInfResource(WEB_XML, "web.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsWebResource(INDEX_JSP, "index.jsp");
}
@Test
public void shouldReadProperties(@ArquillianResource URL url) throws Exception {
HttpRequest.get(url + "index.jsp", 10, TimeUnit.SECONDS);
}
}
| 2,206
| 40.641509
| 141
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/jsp/taglib/external/ExternalTag.java
|
package org.jboss.as.test.integration.web.jsp.taglib.external;
import java.io.IOException;
import jakarta.servlet.jsp.JspException;
import jakarta.servlet.jsp.JspWriter;
import jakarta.servlet.jsp.tagext.SimpleTagSupport;
/**
* @author Stuart Douglas
*/
public class ExternalTag extends SimpleTagSupport {
@Override
public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
out.println("External Tag!");
}
}
| 479
| 25.666667
| 62
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/jsp/taglib/external/InternalTag.java
|
package org.jboss.as.test.integration.web.jsp.taglib.external;
import java.io.IOException;
import jakarta.servlet.jsp.JspException;
import jakarta.servlet.jsp.JspWriter;
import jakarta.servlet.jsp.tagext.SimpleTagSupport;
/**
* @author Stuart Douglas
*/
public class InternalTag extends SimpleTagSupport {
@Override
public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
out.println("Internal Tag!");
}
}
| 479
| 25.666667
| 62
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/jsp/taglib/external/ExternalTagLibTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.jsp.taglib.external;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.module.util.TestModule;
import org.jboss.as.test.shared.ModuleUtils;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
@RunAsClient
public class ExternalTagLibTestCase {
private static final String BOTH_DEPENDENCIES_WAR = "both-dependencies.war";
private static final String EXTERNAL_DEPENDENCY_ONLY_WAR = "external-dependency-only.war";
private static final String MODULE_NAME = "external-tag-lib";
private static final String TEST_JSP = "test.jsp";
private static TestModule testModule;
private static final boolean isRunningWithBootableJar = Boolean.getBoolean("ts.bootable");
@AfterClass
public static void tearDown() throws Exception {
if (!isRunningWithBootableJar) {
testModule.remove();
}
}
@Deployment(name = EXTERNAL_DEPENDENCY_ONLY_WAR, order = 1)
public static WebArchive deployment() throws Exception {
//when running with bootable JAR, the module is packed into JAR before tests are run
if (!isRunningWithBootableJar) {
createExternalTaglibModule();
}
return ShrinkWrap.create(WebArchive.class, EXTERNAL_DEPENDENCY_ONLY_WAR)
.addAsManifestResource(new StringAsset("Dependencies: test." + MODULE_NAME + " meta-inf\n"), "MANIFEST.MF")
.addAsWebResource(getJspAsset(false), TEST_JSP);
}
@Deployment(name = BOTH_DEPENDENCIES_WAR, order = 2)
public static WebArchive deployWithBothDependencies() throws Exception {
return ShrinkWrap.create(WebArchive.class, BOTH_DEPENDENCIES_WAR)
.addClass(InternalTag.class)
.addAsWebInfResource(ExternalTagLibTestCase.class.getPackage(), "internal.tld", "internal.tld")
.addAsManifestResource(new StringAsset("Dependencies: test." + MODULE_NAME + " meta-inf\n"), "MANIFEST.MF")
.addAsWebResource(getJspAsset(true), TEST_JSP);
}
@ArquillianResource
@OperateOnDeployment(BOTH_DEPENDENCIES_WAR)
private URL both_dependencies_url;
@ArquillianResource
@OperateOnDeployment(EXTERNAL_DEPENDENCY_ONLY_WAR)
private URL external_dependency_only_url;
@Test
public void testExternalTagLibOnly() throws Exception {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpget = new HttpGet(external_dependency_only_url.toExternalForm() + TEST_JSP);
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
Assert.assertTrue(result, result.contains("External Tag!"));
}
}
@Test
public void testExternalAndInternalTagLib() throws Exception {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpget = new HttpGet(both_dependencies_url.toExternalForm() + TEST_JSP);
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
Assert.assertTrue(result, result.contains("External Tag!"));
Assert.assertTrue(result, result.contains("Internal Tag!"));
}
}
private static void createExternalTaglibModule() throws Exception {
testModule = ModuleUtils.createTestModuleWithEEDependencies(MODULE_NAME);
JavaArchive jar = testModule.addResource("module.jar");
jar.addClass(ExternalTag.class);
jar.addAsManifestResource(ExternalTagLibTestCase.class.getPackage(), "external.tld", "external.tld");
testModule.create(true);
}
private static StringAsset getJspAsset(boolean withInternalLib) {
String optionalInternalTagLib = withInternalLib ? "<%@ taglib prefix=\"i\" uri=\"http://internal.taglib\" %>\n" : "";
String optionalInternalTag = withInternalLib ? " <i:test/>\n" : "";
return new StringAsset(
"<%@ taglib prefix=\"e\" uri=\"http://external.taglib\" %>\n" +
optionalInternalTagLib +
"<html>\n" +
" <head>\n" +
" <title>test</title>\n" +
" </head>\n" +
" <body>\n" +
" <e:test/>\n" +
optionalInternalTag +
" </body>\n" +
"</html>");
}
}
| 6,460
| 43.558621
| 125
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/jsp/taglib/jar/TagLibInJarTestCase.java
|
/*
* Copyright 2018 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.integration.web.jsp.taglib.jar;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
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;
@RunWith(Arquillian.class)
@RunAsClient
public class TagLibInJarTestCase {
private static final String TLD_INSIDE_RESOURCES = "tld-inside-resources";
private static final String TLD_OUTSIDE_RESOURCES = "tld-outside-resources";
private static final String TLD_INSIDE_JAR = "tld-inside-jar";
private static final String JAR_NAME = "taglib.jar";
private static final String JSP = "index.jsp";
private static final String WEB_FRAGMENT = "web-fragment.xml";
@ArquillianResource
@OperateOnDeployment(TLD_OUTSIDE_RESOURCES)
private URL urlDep1;
@ArquillianResource
@OperateOnDeployment(TLD_INSIDE_RESOURCES)
private URL urlDep2;
@ArquillianResource
@OperateOnDeployment(TLD_INSIDE_JAR)
private URL urlDep3;
@Deployment(name = TLD_OUTSIDE_RESOURCES)
public static WebArchive deployment1() throws Exception {
return createDeployment(TLD_OUTSIDE_RESOURCES + ".war", "tlds/taglib.tld");
}
@Deployment(name = TLD_INSIDE_RESOURCES)
public static WebArchive deployment2() throws Exception {
return createDeployment(TLD_INSIDE_RESOURCES + ".war", "resources/tlds/taglib.tld");
}
@Deployment(name = TLD_INSIDE_JAR)
public static WebArchive deployment3() throws Exception {
return createDeployment3(TLD_INSIDE_JAR + ".war");
}
private static WebArchive createDeployment(String name, String tldLocation) throws Exception {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, JAR_NAME)
.addAsManifestResource(TagLibInJarTestCase.class.getPackage(), "taglib.tld", tldLocation)
.addAsManifestResource(TagLibInJarTestCase.class.getPackage(), WEB_FRAGMENT, WEB_FRAGMENT)
.addClass(TestTag.class);
WebArchive war = ShrinkWrap.create(WebArchive.class, name)
.addAsLibraries(jar)
.addAsWebResource(TagLibInJarTestCase.class.getPackage(), JSP, JSP);
return war;
}
private static WebArchive createDeployment3(String name) throws Exception {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, JAR_NAME)
.addAsManifestResource(TagLibInJarTestCase.class.getPackage(), "taglibInJar.tld", "tlds/taglibInJar.tld")
.addClass(TestTag.class);
WebArchive war = ShrinkWrap.create(WebArchive.class, name)
.addAsLibraries(jar)
.addAsWebInfResource(TagLibInJarTestCase.class.getPackage(), "web.xml", "web.xml")
.addAsWebResource(TagLibInJarTestCase.class.getPackage(), JSP, JSP);
return war;
}
@Test
@OperateOnDeployment(TLD_OUTSIDE_RESOURCES)
public void testTldOutsideResourcesFolder() throws Exception {
checkJspAvailable(urlDep1);
}
@Test
@OperateOnDeployment(TLD_INSIDE_RESOURCES)
public void testTldInsideResourcesFolder() throws Exception {
checkJspAvailable(urlDep2);
}
/**
* Tests if deployment with taglib-location pointing to jar fails during deployment phase.
* Test passes if the correct response is returned from the Jakarta Server Pages.
*
* @throws Exception
*/
@Test
@OperateOnDeployment(TLD_INSIDE_JAR)
public void testTldInsideJar() throws Exception {
checkJspAvailable(urlDep3);
}
private void checkJspAvailable(URL url) throws Exception {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
String jspUrl = url.toExternalForm() + JSP;
HttpGet httpget = new HttpGet(jspUrl);
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
Assert.assertTrue(result, result.contains("Test Tag!"));
}
}
}
| 5,292
| 38.207407
| 121
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/jsp/taglib/jar/TestTag.java
|
/*
* Copyright 2018 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.integration.web.jsp.taglib.jar;
import java.io.IOException;
import jakarta.servlet.jsp.JspException;
import jakarta.servlet.jsp.JspWriter;
import jakarta.servlet.jsp.tagext.SimpleTagSupport;
/**
* @author Stuart Douglas
*/
public class TestTag extends SimpleTagSupport {
@Override
public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
out.println("Test Tag!");
}
}
| 1,062
| 30.264706
| 75
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/customerrors/ContextForwardServlet.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.customerrors;
import java.io.IOException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletContext;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletConfig;
import org.jboss.logging.Logger;
/**
* A generic fowarding servlet that obtains the ServletContext for the
* forwardContext init-param and then obtain a request dispatcher for the
* request.getPathInfo and forward the request. This allows a global servlet
* mapping to redirect requests to a common target. An example would be a global
* web.xml error-pages with a single shared context for the web pages. This
* requires that the web context crossContext attribute is set to true.
*
* @author Scott.Stark@jboss.org
*/
public class ContextForwardServlet extends HttpServlet {
private static final long serialVersionUID = -853278446594804509L;
private static Logger log = Logger.getLogger(ContextForwardServlet.class);
/** The name of the context to which requests are forwarded */
private String forwardContext = "/error-pages";
public void init(ServletConfig config) throws ServletException {
super.init(config);
String param = config.getInitParameter("forwardContext");
if (param != null)
forwardContext = param;
}
/**
* Lookup the ServletContext associated with the forwardContext init-param
* and then obtain a request dispatcher for the request.getPathInfo and
* forward the request. This allows a global servlet mapping to redirect
* requests to a common target.
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (log.isTraceEnabled()) {
log.trace("[" + forwardContext + "], PathInfo: " + request.getPathInfo() + ", QueryString: "
+ request.getQueryString() + ", ContextPath: " + request.getContextPath() + ", HeaderNames: "
+ request.getHeaderNames() + ", isCommitted: " + response.isCommitted());
}
String path = request.getPathInfo();
ServletContext sc = getServletContext().getContext(forwardContext);
if (sc != null) {
if (log.isTraceEnabled())
log.trace("Found ServletContext for: " + forwardContext);
RequestDispatcher rd = sc.getRequestDispatcher(path);
if (rd != null) {
if (log.isTraceEnabled())
log.trace("Found RequestDispatcher for: " + path);
rd.forward(request, response);
return;
}
}
throw new ServletException("No RequestDispatcher for: " + forwardContext + "/" + path);
}
}
| 4,034
| 41.473684
| 121
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/customerrors/CustomErrorsUnitTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.customerrors;
import static org.junit.Assert.assertTrue;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.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.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests of custom error forwarding
*
* @author Scott.Stark@jboss.org
* @author lbarreiro@redhat.com
*/
@RunWith(Arquillian.class)
@RunAsClient
public class CustomErrorsUnitTestCase {
private static Logger log = Logger.getLogger(CustomErrorsUnitTestCase.class);
@Deployment(name = "custom-errors.war", testable = false)
public static WebArchive errorDeployment() {
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
String resourcesLocation = "org/jboss/as/test/integration/web/customerrors/resources/";
WebArchive war = ShrinkWrap.create(WebArchive.class, "custom-errors.war");
war.setWebXML(tccl.getResource(resourcesLocation + "custom-errors-web.xml"));
war.addAsWebResource(tccl.getResource(resourcesLocation + "403.jsp"), "403.jsp");
war.addAsWebResource(tccl.getResource(resourcesLocation + "404.jsp"), "404.jsp");
war.addAsWebResource(tccl.getResource(resourcesLocation + "500.jsp"), "500.jsp");
war.addAsManifestResource(CustomErrorsUnitTestCase.class.getPackage(), "permissions.xml", "permissions.xml");
war.addClass(ErrorGeneratorServlet.class);
return war;
}
@Deployment(name = "error-producer.war", testable = false)
public static WebArchive producerDeployment() {
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
String resourcesLocation = "org/jboss/as/test/integration/web/customerrors/resources/";
WebArchive war = ShrinkWrap.create(WebArchive.class, "error-producer.war");
war.setWebXML(tccl.getResource(resourcesLocation + "error-producer-web.xml"));
war.addAsManifestResource(CustomErrorsUnitTestCase.class.getPackage(), "permissions.xml", "permissions.xml");
war.addClass(ErrorGeneratorServlet.class);
war.addClass(ContextForwardServlet.class);
return war;
}
/**
* Test that the custom 404 error page is seen
*
* @throws Exception
*/
@Test
@OperateOnDeployment("error-producer.war")
public void test404Error(@ArquillianResource(ErrorGeneratorServlet.class) URL baseURL) throws Exception {
int errorCode = HttpURLConnection.HTTP_NOT_FOUND;
URL url = new URL(baseURL + "/ErrorGeneratorServlet?errorCode=" + errorCode);
testURL(url, errorCode, "404.jsp", null);
}
/**
* Test that the custom 500 error page is seen
*
* @throws Exception
*/
@Test
@OperateOnDeployment("error-producer.war")
public void test500Error(@ArquillianResource(ErrorGeneratorServlet.class) URL baseURL) throws Exception {
int errorCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
URL url = new URL(baseURL + "/ErrorGeneratorServlet?errorCode=" + errorCode);
testURL(url, errorCode, "500.jsp", null);
}
/**
* Test that the custom 500 error page is seen for an exception
*
* @throws Exception
*/
@Test
@OperateOnDeployment("error-producer.war")
public void testExceptionError(@ArquillianResource(ErrorGeneratorServlet.class) URL baseURL) throws Exception {
URL url = new URL(baseURL + "/ErrorGeneratorServlet");
testURL(url, HttpURLConnection.HTTP_INTERNAL_ERROR, "500.jsp", "java.lang.IllegalStateException");
}
private void testURL(URL url, int expectedCode, String expectedPage, String expectedError) throws Exception {
HttpGet httpget = new HttpGet(url.toURI());
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
log.trace("executing request" + httpget.getRequestLine());
HttpResponse response = httpClient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
Header page = response.getFirstHeader("X-CustomErrorPage");
Header error = response.getFirstHeader("X-ExceptionType");
assertTrue("Wrong response code: " + statusCode, statusCode == expectedCode);
if (expectedPage != null) {
assertTrue("X-CustomErrorPage(" + page + ") is " + expectedPage, page.getValue().equals(expectedPage));
}
if (expectedError != null) {
assertTrue("X-ExceptionType(" + error + ") is " + expectedError, error.getValue().equals(expectedError));
}
}
}
}
| 6,242
| 42.055172
| 121
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/customerrors/ErrorGeneratorServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.customerrors;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* A servlet that sends error responses based on the errorCode parameter.
*
* @author Scott.Stark@jboss.org
*/
public class ErrorGeneratorServlet extends HttpServlet {
private static final long serialVersionUID = 694880881746275204L;
/**
* Issues a response.sendError() for the errorCode parameter passed in.
* If there is no errorCode parameter an IllegalStateException is thrown.
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String errorCode = request.getParameter("errorCode");
if (errorCode == null)
throw new IllegalStateException("No errorCode parameter seen");
int code = Integer.parseInt(errorCode);
response.sendError(code);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
}
| 2,561
| 38.415385
| 130
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/webfragment/WebFragmentAbsoluteOrderingTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.webfragment;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.net.URL;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
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;
/**
* Test absolute ordering works even if some web fragments are missing
* <p>
* see https://issues.jboss.org/browse/WFLY-6552
*/
@RunWith(Arquillian.class)
@RunAsClient
public class WebFragmentAbsoluteOrderingTestCase {
@ArquillianResource
private URL url;
@Deployment
public static WebArchive single() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "single.war");
war.addAsWebInfResource(WebFragmentAbsoluteOrderingTestCase.class.getPackage(), "web.xml", "web.xml");
war.addAsWebResource(new StringAsset("hi"), "index.txt");
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "test.jar");
jar.addAsManifestResource(WebFragmentAbsoluteOrderingTestCase.class.getPackage(), "web-fragment.xml", "web-fragment.xml");
war.addAsLibrary(jar);
return war;
}
private String performCall(URL url, String urlPattern) throws Exception {
return HttpRequest.get(url.toExternalForm() + urlPattern, 1000, SECONDS);
}
@Test
public void testLifeCycle() throws Exception {
Assert.assertEquals("hi", performCall(url, ""));
}
}
| 2,855
| 37.594595
| 130
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/rootcontext/RootContextUtil.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.rootcontext;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALLOW_RESOURCE_SERVICE_RESTART;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.junit.Assert.assertTrue;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.OperationBuilder;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
/**
* @author lbarreiro@redhat.com
*/
public class RootContextUtil {
private static Logger log = Logger.getLogger(RootContextUtil.class);
private static String SERVER = "server";
private static String HOST = "host";
private static final String WEB_SUBSYSTEM_NAME = "undertow";
public static void createVirutalHost(ModelControllerClient client, String virtualHost) throws Exception {
final List<ModelNode> updates = new ArrayList<ModelNode>();
ModelNode op = new ModelNode();
op.get(OP).set(ADD);
op.get(OP_ADDR).add(SUBSYSTEM, WEB_SUBSYSTEM_NAME);
op.get(OP_ADDR).add(SERVER, "default-server");
op.get(OP_ADDR).add(HOST, virtualHost);
op.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true);
op.get("default-web-module").set("somewar.war");
updates.add(op);
applyUpdates(updates, client);
}
public static void removeVirtualHost(final ModelControllerClient client, String virtualHost) throws Exception {
final List<ModelNode> updates = new ArrayList<ModelNode>();
ModelNode op = new ModelNode();
op.get(OP).set(REMOVE);
op.get(OP_ADDR).add(SUBSYSTEM, WEB_SUBSYSTEM_NAME);
op.get(OP_ADDR).add(SERVER, "default-server");
op.get(OP_ADDR).add(HOST, virtualHost);
op.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true);
updates.add(op);
applyUpdates(updates, client);
}
public static void undeploy(final ModelControllerClient client, String deploymentName) throws Exception {
final List<ModelNode> updates = new ArrayList<ModelNode>();
ModelNode op = new ModelNode();
op.get(OP).set(REMOVE);
op.get(OP_ADDR).add(DEPLOYMENT, deploymentName);
updates.add(op);
applyUpdates(updates, client);
}
private static void applyUpdates(final List<ModelNode> updates, final ModelControllerClient client) throws Exception {
for (ModelNode update : updates) {
log.trace("+++ Update on " + client + ":\n" + update.toString());
ModelNode result = client.execute(new OperationBuilder(update).build());
if (result.hasDefined("outcome") && "success".equals(result.get("outcome").asString())) {
if (result.hasDefined("result"))
log.trace(result.get("result"));
} else if (result.hasDefined("failure-description")) {
throw new RuntimeException(result.get("failure-description").toString());
} else {
throw new RuntimeException("Operation not successful; outcome = " + result.get("outcome"));
}
}
}
/**
* Access http://localhost/
*/
public static String hitRootContext(URL url, String serverName) throws Exception {
HttpGet httpget = new HttpGet(url.toURI());
HttpClient httpclient = HttpClients.createDefault();
httpget.setHeader("Host", serverName);
log.trace("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
Header[] errorHeaders = response.getHeaders("X-Exception");
assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
assertTrue("X-Exception(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
return EntityUtils.toString(response.getEntity());
}
}
| 5,964
| 42.540146
| 122
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/rootcontext/RootContextEarUnitTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.rootcontext;
import java.net.URL;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.integration.management.base.AbstractMgmtServerSetupTask;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertTrue;
/**
* This class tests a root context deployed as an EAR or a WAR.
*
* @author Stan.Silvert@jboss.org
* @author lbarreiro@redhat.com
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(RootContextEarUnitTestCase.RootContextEarUnitTestCaseSetup.class)
public class RootContextEarUnitTestCase {
static class RootContextEarUnitTestCaseSetup extends AbstractMgmtServerSetupTask {
@Override
protected void doSetup(final ManagementClient managementClient) throws Exception {
RootContextUtil.createVirutalHost(managementClient.getControllerClient(), HOST);
}
@Override
public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception {
RootContextUtil.removeVirtualHost(managementClient.getControllerClient(), HOST);
}
}
private static String HOST = "context-host";
@Deployment(name = "root-web.ear")
public static EnterpriseArchive earDeployment() {
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
String resourcesLocation = "org/jboss/as/test/integration/web/rootcontext/resources/";
WebArchive war = ShrinkWrap.create(WebArchive.class, "root-web.war");
war.setWebXML(tccl.getResource(resourcesLocation + "root-web.xml"));
war.addAsWebInfResource(tccl.getResource(resourcesLocation + "jboss-web.xml"), "jboss-web.xml");
war.addAsWebResource(tccl.getResource(resourcesLocation + "index.html"), "index.html");
EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "root-web.ear");
ear.setApplicationXML(tccl.getResource(resourcesLocation + "application-root.xml"));
ear.addAsModule(war);
return ear;
}
@Test
public void testRootContextEAR(@ArquillianResource URL url) throws Exception {
String response = RootContextUtil.hitRootContext(url, HOST);
assertTrue(response.contains("A Root Context Page"));
}
}
| 3,768
| 39.095745
| 114
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/rootcontext/RootContextWarUnitTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.rootcontext;
import java.net.URL;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertTrue;
/**
* This class tests a root context deployed as an EAR or a WAR.
*
* @author Stan.Silvert@jboss.org
* @author lbarreiro@redhat.com
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(RootContextWarUnitTestCase.RootContextWarSetup.class)
public class RootContextWarUnitTestCase {
private static String HOST = "context-host";
static class RootContextWarSetup implements ServerSetupTask {
@Override
public void setup(final ManagementClient managementClient, final String containerId) throws Exception {
RootContextUtil.createVirutalHost(managementClient.getControllerClient(), HOST);
}
@Override
public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception {
RootContextUtil.removeVirtualHost(managementClient.getControllerClient(), HOST);
}
}
@Deployment(name = "root-context.war")
public static WebArchive warDeployment() {
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
String resourcesLocation = "org/jboss/as/test/integration/web/rootcontext/resources/";
WebArchive war = ShrinkWrap.create(WebArchive.class, "root-context.war");
war.setWebXML(tccl.getResource(resourcesLocation + "root-web.xml"));
war.addAsWebInfResource(tccl.getResource(resourcesLocation + "jboss-web.xml"), "jboss-web.xml");
war.addAsWebResource(tccl.getResource(resourcesLocation + "index.html"), "index.html");
return war;
}
@Test
public void testRootContextWAR(@ArquillianResource URL url) throws Exception {
String response = RootContextUtil.hitRootContext(url, HOST);
assertTrue(response.contains("A Root Context Page"));
}
}
| 3,454
| 38.261364
| 114
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/websocket/WebSocketTestCase.java
|
package org.jboss.as.test.integration.web.websocket;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.io.IOException;
import java.net.SocketPermission;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.PropertyPermission;
import jakarta.websocket.ContainerProvider;
import jakarta.websocket.DeploymentException;
import jakarta.websocket.Session;
import jakarta.websocket.WebSocketContainer;
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.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.Test;
import org.junit.runner.RunWith;
/**
* Simple smoke test for WebSockets. It tests both basic use-cases - WebSocket client either as a standalone application
* or as a part of a WAR-deployment.
*
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
public class WebSocketTestCase {
private static final String CLIENT_STANDALONE = "standalone";
private static final String CLIENT_IN_DEPLOYMENT = "indeployment";
@Deployment(testable = false, name = CLIENT_STANDALONE)
public static WebArchive createThinDeployment() {
return createBasicDeployment(CLIENT_STANDALONE);
}
@Deployment(name = CLIENT_IN_DEPLOYMENT)
public static WebArchive createRichDeployment() {
return createBasicDeployment(CLIENT_IN_DEPLOYMENT)
.addClasses(WebSocketTestCase.class, AnnotatedClient.class, TestSuiteEnvironment.class)
.addAsManifestResource(
createPermissionsXmlAsset(
// Needed for the TestSuiteEnvironment.getServerAddress()
new PropertyPermission("management.address", "read"), new PropertyPermission("node0", "read"),
new PropertyPermission("jboss.http.port", "read"),
// Needed for the serverContainer.connectToServer()
new SocketPermission(
TestSuiteEnvironment.getServerAddress() + ":" + TestSuiteEnvironment.getHttpPort(),
"connect,resolve"),
// Needed for xnio's WorkerThread which binds to Xnio.ANY_INET_ADDRESS, see WFLY-7538
new SocketPermission("*:0", "listen,resolve")),
"permissions.xml");
}
@Test
@OperateOnDeployment(CLIENT_STANDALONE)
@RunAsClient
public void testClientStandalone(@ArquillianResource URL webapp) throws Exception {
assertWebSocket(webapp);
}
@Test
@OperateOnDeployment(CLIENT_IN_DEPLOYMENT)
public void testClientInDeployment(@ArquillianResource URL webapp) throws Exception {
assertWebSocket(webapp);
}
private void assertWebSocket(URL webapp) throws InterruptedException, IOException, DeploymentException, URISyntaxException {
AnnotatedClient endpoint = new AnnotatedClient();
WebSocketContainer serverContainer = ContainerProvider.getWebSocketContainer();
try (Session session = serverContainer.connectToServer(endpoint,
new URI("ws", "", TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getHttpPort(),
webapp.getPath() + "websocket/Stuart", "", ""))) {
Assert.assertEquals("Hello Stuart", endpoint.getMessage());
}
}
/**
* Creates basic deployment with given name for WebSocket endpoint.
*
* @param name deployment name
* @return Shrinkwrap WebArchive instance
*/
private static WebArchive createBasicDeployment(String name) {
return ShrinkWrap.create(WebArchive.class, name + ".war")
.addClasses(AnnotatedEndpoint.class)
.addAsManifestResource(new StringAsset("io.undertow.websockets.jsr.UndertowContainerProvider"),
"services/jakarta.websocket.ContainerProvider");
}
}
| 4,441
| 42.54902
| 128
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/websocket/AnnotatedEndpoint.java
|
package org.jboss.as.test.integration.web.websocket;
import jakarta.websocket.OnMessage;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
/**
* @author Stuart Douglas
*/
@ServerEndpoint("/websocket/{name}")
public class AnnotatedEndpoint {
@OnMessage
public String message(String message, @PathParam("name") String name) {
return message + " " + name;
}
}
| 424
| 21.368421
| 75
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/websocket/AnnotatedClient.java
|
package org.jboss.as.test.integration.web.websocket;
import java.io.IOException;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import jakarta.websocket.ClientEndpoint;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
/**
* @author Stuart Douglas
*/
@ClientEndpoint
public class AnnotatedClient {
private final BlockingDeque<String> queue = new LinkedBlockingDeque<>();
@OnOpen
public void open(final Session session) throws IOException {
session.getBasicRemote().sendText("Hello");
}
@OnMessage
public void message(final String message) {
queue.add(message);
}
public String getMessage() throws InterruptedException {
return queue.poll(5, TimeUnit.SECONDS);
}
}
| 870
| 23.194444
| 76
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/cookie/CookieEchoServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.cookie;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Sends a version of the cookie back as a response body content.
*
* @author Jan Stourac
*/
@WebServlet(name = "CookieEchoServlet", urlPatterns = {"/CookieEchoServlet"})
public class CookieEchoServlet extends HttpServlet {
private static final long serialVersionUID = -5891682551205336274L;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
Cookie[] cookies = request.getCookies();
PrintWriter out = response.getWriter();
for (Cookie c : cookies) {
out.print(c.getVersion());
}
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
processRequest(request, response);
}
}
| 2,430
| 36.4
| 116
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/cookie/CookieUnitTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.cookie;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test case for cookie
*
* @author prabhat.jha@jboss.com
* @author lbarreiro@redhat.com
*/
@RunWith(Arquillian.class)
@RunAsClient
public class CookieUnitTestCase {
protected static Logger log = Logger.getLogger(CookieUnitTestCase.class);
protected static String[] cookieNames = {"simpleCookie", "withSpace", "commented", "expired"};
protected static final long fiveSeconds = 5000;
@ArquillianResource(CookieServlet.class)
protected URL cookieURL;
@ArquillianResource(CookieReadServlet.class)
protected URL cookieReadURL;
@Deployment(testable = false)
public static WebArchive deployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "jbosstest-cookie.war");
war.addClass(CookieReadServlet.class);
war.addClass(CookieServlet.class);
return war;
}
@Test
public void testCookieSetCorrectly() throws Exception {
log.debug("testCookieSetCorrectly()");
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpResponse response = httpclient.execute(new HttpGet(cookieReadURL.toURI() + "CookieReadServlet"));
if (response.getEntity() != null) { response.getEntity().getContent().close(); }
log.debug("Sending request with cookie");
response = httpclient.execute(new HttpPost(cookieReadURL.toURI() + "CookieReadServlet"));
}
}
@Test
public void testCookieRetrievedCorrectly() throws Exception {
log.trace("testCookieRetrievedCorrectly()");
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpClientContext context = HttpClientContext.create();
HttpResponse response = httpclient.execute(new HttpGet(cookieURL.toURI() + "CookieServlet"), context);
// assert that we are able to hit servlet successfully
int postStatusCode = response.getStatusLine().getStatusCode();
Header[] postErrorHeaders = response.getHeaders("X-Exception");
assertTrue("Wrong response code: " + postStatusCode, postStatusCode == HttpURLConnection.HTTP_OK);
assertTrue("X-Exception(" + Arrays.toString(postErrorHeaders) + ") is null", postErrorHeaders.length == 0);
List<Cookie> cookies = context.getCookieStore().getCookies();
assertTrue("Sever did not set expired cookie on client", checkNoExpiredCookie(cookies));
for (Cookie cookie : cookies) {
log.trace("Cookie : " + cookie);
String cookieName = cookie.getName();
String cookieValue = cookie.getValue();
if (cookieName.equals("simpleCookie")) {
assertTrue("cookie value should be jboss", cookieValue.equals("jboss"));
assertEquals("cookie path", "/jbosstest-cookie", cookie.getPath());
assertEquals("cookie persistence", false, cookie.isPersistent());
} else if (cookieName.equals("withSpace")) {
assertEquals("should be no quote in cookie with space", cookieValue.indexOf("\""), -1);
} else if (cookieName.equals("comment")) {
log.trace("comment in cookie: " + cookie.getComment());
// RFC2109:Note that there is no Comment attribute in the Cookie request header
// corresponding to the one in the Set-Cookie response header. The user
// agent does not return the comment information to the origin server.
assertTrue(cookie.getComment() == null);
} else if (cookieName.equals("withComma")) {
assertTrue("should contain a comma", cookieValue.indexOf(",") != -1);
} else if (cookieName.equals("expireIn10Sec")) {
Date now = new Date();
log.trace("will sleep for 5 seconds to see if cookie expires");
assertTrue("cookies should not be expired by now", !cookie.isExpired(new Date(now.getTime() + fiveSeconds)));
log.trace("will sleep for 5 more secs and it should expire");
assertTrue("cookies should be expired by now", cookie.isExpired(new Date(now.getTime() + 2 * fiveSeconds)));
}
}
}
}
protected boolean checkNoExpiredCookie(List<Cookie> cookies) {
for (Cookie cookie : cookies) { if (cookie.getName().equals("expired")) { return false; } }
return true;
}
}
| 6,613
| 43.993197
| 129
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/cookie/CookieReadServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.cookie;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jboss.logging.Logger;
@WebServlet(name = "CookieReadServlet", urlPatterns = { "/CookieReadServlet" })
public class CookieReadServlet extends HttpServlet {
private static final long serialVersionUID = 2621436577320182272L;
Logger log = Logger.getLogger(CookieReadServlet.class);
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Cookie Read Servlet</title></head><body><pre>");
Cookie[] cookies = request.getCookies();
if (cookies == null) {
log.trace("cookie is null");
setCookies(request, response);
out.println("Server set cookies correctly");
} else {
for (int i = 0; i < cookies.length; i++) {
Cookie c = cookies[i];
out.println("Cookie" + i + "Name " + c.getName() + " value=" + c.getValue());
if (c.getName().equals("hasSpace") && c.getValue().indexOf("\"") != -1) {
log.debug("Cookie name: " + c.getName() + " cookie value: " + c.getValue());
throw new ServletException("cookie with space not retrieved correctly");
} else if (c.getName().equals("hasComma") && c.getValue().indexOf("\"") != -1) {
log.debug("Cookie name: " + c.getName() + " cookie value: " + c.getValue());
throw new ServletException("cookie with comma not retrieved correctly");
}
}
out.println("Server read cookie correctly");
}
out.println("</pre></body></html>");
out.close();
}
public void setCookies(HttpServletRequest request, HttpServletResponse response) {
response.addCookie(new Cookie("hasSpace", "has space"));
response.addCookie(new Cookie("hasComma", "has,comma"));
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
}
| 3,777
| 43.97619
| 130
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/cookie/DefaultCookieVersionTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.cookie;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.Locale;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
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.impl.cookie.BasicClientCookie;
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.ContainerResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.as.test.shared.SnapshotRestoreSetupTask;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test case for default cookie version configuration.
*
* @author Stuart Douglas
* @author Jan Stourac
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(SnapshotRestoreSetupTask.class)
public class DefaultCookieVersionTestCase {
@ArquillianResource(SimpleCookieServlet.class)
protected URL cookieURL;
private static String DEF_SERVLET_ADDR = "/subsystem=undertow/servlet-container=default";
@Deployment
public static WebArchive deployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "jbosstest-cookie.war");
war.addClass(SimpleCookieServlet.class);
war.addClass(CookieEchoServlet.class);
return war;
}
@ContainerResource
private static ManagementClient managementClient;
@Test
public void testDefaultCookieVersion0() throws Exception {
commonDefaultCookieVersion(0);
}
@Test
public void testSendCookieVersion0() throws Exception {
commonSendCookieVersion(0);
}
private void commonDefaultCookieVersion(int cookieVersion) throws IOException, URISyntaxException {
configureDefaultCookieVersion(cookieVersion);
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpResponse response = httpclient.execute(new HttpGet(cookieURL.toURI() + "SimpleCookieServlet"));
if (response.getEntity() != null) {
response.getEntity().getContent().close();
}
response = httpclient.execute(new HttpPost(cookieURL.toURI() + "SimpleCookieServlet"));
Header[] cookies = response.getHeaders("set-cookie");
Assert.assertTrue(cookies.length > 0);
for (Header i : cookies) {
String value = i.getValue();
Assert.assertFalse(value + Arrays.toString(cookies), value.toLowerCase(Locale.ENGLISH).contains("version"));
}
}
}
private void commonSendCookieVersion(int cookieVersion) throws IOException, URISyntaxException {
configureDefaultCookieVersion(cookieVersion);
BasicCookieStore basicCookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("testCookie", "testCookieValue");
cookie.setVersion(cookieVersion);
cookie.setDomain(cookieURL.getHost());
basicCookieStore.addCookie(cookie);
try (CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultCookieStore(basicCookieStore)
.build()) {
HttpResponse response = httpclient.execute(new HttpGet(cookieURL.toURI() + "CookieEchoServlet"));
if (response.getEntity() != null) {
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(cookieVersion + "", EntityUtils.toString(response.getEntity()));
}
}
}
private static void configureDefaultCookieVersion(Integer cookieVer) throws IOException {
ModelNode modelNode = new ModelNode();
modelNode.get(ModelDescriptionConstants.OP_ADDR).set(PathAddress.parseCLIStyleAddress(DEF_SERVLET_ADDR)
.toModelNode());
modelNode.get(ModelDescriptionConstants.NAME).set("default-cookie-version");
if (cookieVer != null) {
modelNode.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION);
modelNode.get(ModelDescriptionConstants.VALUE).set(cookieVer);
} else {
modelNode.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION);
}
ModelNode opRes = managementClient.getControllerClient().execute(modelNode);
Assert.assertEquals(opRes.toString(), "success", opRes.get(ModelDescriptionConstants.OUTCOME).asString());
ServerReload.executeReloadAndWaitForCompletion(managementClient);
}
}
| 6,461
| 40.423077
| 124
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/cookie/CookieServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.cookie;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* A servlet that is used to test different way of setting and retrieving cookies.
*
* @author prabhat.jha@jboss.com
*/
@WebServlet(name = "CookieServlet", urlPatterns = { "/CookieServlet" })
public class CookieServlet extends HttpServlet {
private static final long serialVersionUID = -5891682551205336273L;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Cookie Servlet</title></head><body><pre>");
setRFC2109cookies(request, response);
out.println("sever set some cookies. verify on the client that you can see them");
out.println("</pre></body></html>");
out.close();
}
private void setRFC2109cookies(HttpServletRequest request, HttpServletResponse response) {
// A very simple cookie
Cookie cookie = new Cookie("simpleCookie", "jboss");
response.addCookie(cookie);
// A cookie with space in the value. As per ASPATCH-70, there has been some issue with this.
cookie = new Cookie("withSpace", "jboss rocks");
response.addCookie(cookie);
// cookie with comment
// TODO read servlet 2.5 spec and rfc2109, then re-fix it
/*
* Servlet 2.5 Cookie.java disable comment attribute
* cookie = new Cookie("comment", "commented cookie");
* cookie.setComment("This is a comment");
* response.addCookie(cookie);
*/
// cookie with expiry time. This cookie must not be set on client side
cookie = new Cookie("expired", "expired cookie");
cookie.setMaxAge(0);
response.addCookie(cookie);
cookie = new Cookie("withComma", "little,comma");
response.addCookie(cookie);
cookie = new Cookie("expireIn10Sec", "will expire in 10 seconds");
cookie.setMaxAge(10);
response.addCookie(cookie);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
}
| 3,815
| 39.595745
| 130
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/cookie/SimpleCookieServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.cookie;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* A servlet that is used to test different way of setting and retrieving cookies.
*
* @author prabhat.jha@jboss.com
* @author Jan Stourac
*/
@WebServlet(name = "SimpleCookieServlet", urlPatterns = {"/SimpleCookieServlet"})
public class SimpleCookieServlet extends HttpServlet {
private static final long serialVersionUID = -5891682551205336273L;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Cookie Servlet</title></head><body><pre>");
setSimplecookie(request, response);
out.println("sever set some cookies. verify on the client that you can see them");
out.println("</pre></body></html>");
out.close();
}
private void setSimplecookie(HttpServletRequest request, HttpServletResponse response) {
// A very simple cookie
Cookie cookie = new Cookie("simpleCookie", "jboss");
response.addCookie(cookie);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
processRequest(request, response);
}
}
| 2,916
| 38.958904
| 116
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/servlet/pathmapping/PathMappingServlet.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.integration.web.servlet.pathmapping;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = ("/mapping/*"), name = "PathMappingServlet")
public class PathMappingServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write(req.getHttpServletMapping().getMatchValue() + ":" + req.getHttpServletMapping().getPattern() + ":" + req.getHttpServletMapping().getServletName());
}
}
| 1,776
| 44.564103
| 178
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/servlet/pathmapping/ServletMappingMatchTestCase.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.integration.web.servlet.pathmapping;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
@RunAsClient
public class ServletMappingMatchTestCase {
@ArquillianResource
private URL url;
@Deployment(testable = false)
public static Archive<?> getDeployment() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, "war-mapping.war");
war.addPackage(ServletMappingMatchTestCase.class.getPackage());
return war;
}
@Test
public void testServlet() throws Exception {
String s = performCall("mapping/foo", "Hello");
Assert.assertEquals("foo:/mapping/*:PathMappingServlet", s);
}
private String performCall(String urlPattern, String param) throws Exception {
URL url = new URL(this.url.toExternalForm() + urlPattern + "?input=" + param);
return HttpRequest.get(url.toExternalForm(), 10, TimeUnit.SECONDS);
}
}
| 2,510
| 37.630769
| 86
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/servlet/enc/empty/EmptyServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.servlet.enc.empty;
import java.io.IOException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.Assert;
/**
* @author <a href="mailto:cdewolf@redhat.com">Carlo de Wolf</a>
*/
@WebServlet(name="SimpleServlet", urlPatterns={"/simple"})
public class EmptyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
final InitialContext ic = new InitialContext();
ic.lookup("java:comp/env");
Assert.assertFalse(ic.list("java:comp/env").hasMore());
resp.getWriter().write("ok");
resp.getWriter().close();
} catch (NamingException e) {
throw new RuntimeException(e);
}
}
}
| 2,115
| 36.122807
| 113
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/servlet/enc/empty/EmptyCompEnvTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.servlet.enc.empty;
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.test.integration.common.HttpRequest;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals;
/**
*/
@RunWith(Arquillian.class)
@RunAsClient
public class EmptyCompEnvTestCase {
@ArquillianResource
@OperateOnDeployment("empty")
private URL empty;
@Deployment(name = "empty")
public static WebArchive empty() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "empty.war");
war.addClasses(HttpRequest.class, EmptyServlet.class);
return war;
}
private String performCall(URL url,String urlPattern) throws Exception {
return HttpRequest.get(url.toExternalForm() + urlPattern, 1000, SECONDS);
}
@Test
@OperateOnDeployment("empty")
public void testEmptyList() throws Exception {
String result = performCall(empty, "simple");
assertEquals("ok", result);
}
}
| 2,470
| 34.811594
| 81
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/servlet/overlays/PathAccessCheckServlet.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.integration.web.servlet.overlays;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
/**
* @author Jaikiran Pai
*/
@WebServlet(name = "PathAccessCheckServlet", urlPatterns = {"/check-path-access"})
public class PathAccessCheckServlet extends HttpServlet {
static final String ACCESS_CHECKS_CORRECTLY_VALIDATED = "access-checks-valid";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final String path = req.getParameter("path");
final String shouldBeAccessible = req.getParameter("expected-accessible");
final boolean expectedAccessible = shouldBeAccessible == null ? false : Boolean.parseBoolean(shouldBeAccessible);
try (InputStream is = req.getServletContext().getResourceAsStream(path)) {
if (expectedAccessible && is == null) {
throw new ServletException("Expected to be accessible but could not access " + path);
}
if (!expectedAccessible && is != null) {
throw new ServletException("Expected to be inaccessible but could access " + path);
}
}
resp.getWriter().write(ACCESS_CHECKS_CORRECTLY_VALIDATED);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doGet(req, resp);
}
}
| 2,710
| 40.707692
| 121
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/servlet/overlays/ServletResourceOverlaysTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.servlet.overlays;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.impl.base.path.BasicPath;
import org.jboss.vfs.VFS;
import org.jboss.vfs.VirtualFile;
import org.jboss.vfs.VirtualFilePermission;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.FilePermission;
import java.net.URL;
import java.nio.file.Paths;
import java.util.PropertyPermission;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION;
import static org.jboss.as.test.shared.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(ServletResourceOverlaysTestCase.ServletResourceOverlaysTestCaseServerSetup.class)
public class ServletResourceOverlaysTestCase {
private static final String SUBSYSTEM_NAME = "undertow";
@ArquillianResource
private URL url;
@Deployment
public static WebArchive single() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "single.war");
war.addAsWebResource(new StringAsset("a"), "a.txt");
war.addAsWebResource(new StringAsset("b"), "b.txt");
war.addClass(PathAccessCheckServlet.class);
war.addAsManifestResource(createPermissionsXmlAsset(
new FilePermission("/-", "read"),
new PropertyPermission("java.io.tmpdir","read"),
new VirtualFilePermission(Paths.get(System.getProperty("java.io.tmpdir"), "noaccess.txt").toFile().getAbsolutePath(), "read")
), "permissions.xml");
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "test.jar");
jar.addAsManifestResource(new StringAsset("b - overlay"), new BasicPath("resources", "b.txt"));
jar.addAsManifestResource(new StringAsset("c - overlay"), new BasicPath("resources", "c.txt"));
war.addAsLibrary(jar);
return war;
}
public static class ServletResourceOverlaysTestCaseServerSetup implements ServerSetupTask {
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
ModelNode op = new ModelNode();
op.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
op.get(OP_ADDR).add(SUBSYSTEM, SUBSYSTEM_NAME);
op.get(OP_ADDR).add("server", "default-server");
op.get(OP_ADDR).add("http-server", "default");
op.get(NAME).set("allow-encoded-slash");
op.get(VALUE).set(true);
managementClient.getControllerClient().execute(op);
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
ModelNode op = new ModelNode();
op.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
op.get(OP_ADDR).add(SUBSYSTEM, SUBSYSTEM_NAME);
op.get(OP_ADDR).add("server", "default-server");
op.get(OP_ADDR).add("http-server", "default");
op.get(NAME).set("allow-encoded-slash");
op.get(VALUE).set(false);
managementClient.getControllerClient().execute(op);
}
}
private String performCall(URL url, String urlPattern) throws Exception {
return HttpRequest.get(url.toExternalForm() + urlPattern, 1000, SECONDS);
}
@Test
public void testLifeCycle() throws Exception {
String result = performCall(url, "a.txt");
assertEquals("a", result);
result = performCall(url, "b.txt");
assertEquals("b", result);
result = performCall(url, "c.txt");
assertEquals("c - overlay", result);
}
/**
* Tests that a servlet (through the use of {@link jakarta.servlet.ServletContext#getResourceAsStream(String)} (or similar APIs)
* cannot access paths outside of the deployment
*
* @throws Exception
*/
@Test
public void testPathAccess() throws Exception {
final String aTxtPath = "a.txt";
final String aTxtAccess = performCall(url, "/check-path-access?path=a.txt&expected-accessible=true");
assertEquals("Unexpected result from call to " + aTxtPath, PathAccessCheckServlet.ACCESS_CHECKS_CORRECTLY_VALIDATED, aTxtAccess);
//Deployment root virtual file is different on each Operating System, we have to find out how to navigate to the root folder from the deployed file
VirtualFile deploymentRoot = VFS.getChild("content/single.war");
final StringBuilder accessRootPath = new StringBuilder("");
while (!deploymentRoot.isRoot()) {
accessRootPath.append("/..");
deploymentRoot = deploymentRoot.getParent();
}
final File fileUnderTest = Paths.get(System.getProperty("java.io.tmpdir"), "noaccess.txt").toFile();
fileUnderTest.createNewFile();
if (fileUnderTest.exists()) {
String canonicalPath = fileUnderTest.getCanonicalPath();
canonicalPath = canonicalPath.substring(fileUnderTest.toPath().getRoot().toString().length());
if (File.separator.equals("\\")) {
canonicalPath = canonicalPath.replace("\\", "%5c");
}
final String pathOutsideOfDeployment = accessRootPath.toString() + "/../../../../../../../" + canonicalPath;
final String outsidePathAccessCheck = performCall(url, "/check-path-access?path=" + pathOutsideOfDeployment + "&expected-accessible=false");
assertEquals("Unexpected result from call to " + pathOutsideOfDeployment, PathAccessCheckServlet.ACCESS_CHECKS_CORRECTLY_VALIDATED, outsidePathAccessCheck);
fileUnderTest.delete();
} else {
fail("Cannot create the file under test: " + fileUnderTest.getCanonicalPath());
}
}
}
| 8,006
| 44.754286
| 168
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/servlet/lifecycle/LifeCycleMethodServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.servlet.lifecycle;
import java.io.IOException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
*/
@WebServlet(name = "LifeCycleMethodServlet", urlPatterns = {"/LifeCycleMethodServlet"})
public class LifeCycleMethodServlet extends HttpServlet implements ServletContextListener {
String message;
public void postConstruct() {
message = "ok";
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write(message);
resp.getWriter().close();
}
// test AS7-5746 use case
private static final String NAME = "java:global/env/foo";
private static final String VALUE = "FOO";
@Override
public void contextInitialized(ServletContextEvent sce) {
try {
Context context = new InitialContext();
context.bind(NAME, VALUE);
} catch (NamingException e) {
throw new RuntimeException(e);
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
try {
Context context = new InitialContext();
context.lookup(NAME);
context.unbind(NAME);
} catch (NamingException e) {
throw new RuntimeException(e);
}
}
}
| 2,751
| 32.560976
| 113
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/servlet/lifecycle/ServletLifecycleMethodDescriptorTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.servlet.lifecycle;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.assertEquals;
import java.net.URL;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.common.HttpRequest;
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.naming.java.permission.JndiPermission;
/**
*/
@RunWith(Arquillian.class)
@RunAsClient
public class ServletLifecycleMethodDescriptorTestCase {
@ArquillianResource
private URL url;
@Deployment
public static WebArchive single() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "single.war");
war.addClasses(HttpRequest.class, LifeCycleMethodServlet.class);
war.addAsWebInfResource(ServletLifecycleMethodDescriptorTestCase.class.getPackage(), "web.xml", "web.xml");
war.addAsManifestResource(createPermissionsXmlAsset(new JndiPermission("java:global/env/foo", "bind")), "permissions.xml");
return war;
}
private String performCall(URL url, String urlPattern) throws Exception {
return HttpRequest.get(url.toExternalForm() + urlPattern, 1000, SECONDS);
}
@Test
public void testLifeCycle() throws Exception {
String result = performCall(url, "LifeCycleMethodServlet");
assertEquals("ok", result);
}
}
| 2,776
| 38.671429
| 131
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/formauth/FormAuthUnitTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.formauth;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.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.container.ManagementClient;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests of form authentication
*
* @author Scott.Stark@jboss.org
* @author lbarreiro@redhat.com
*/
@RunWith(Arquillian.class)
@RunAsClient
public class FormAuthUnitTestCase {
private static Logger log = Logger.getLogger(FormAuthUnitTestCase.class);
@ArquillianResource
private URL baseURLNoAuth;
@ArquillianResource
private ManagementClient managementClient;
private static final String USERNAME = "user2";
private static final String PASSWORD = "password2";
DefaultHttpClient httpclient = new DefaultHttpClient();
@Deployment(name="form-auth.war", testable = false)
public static WebArchive deployment() {
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
String resourcesLocation = "org/jboss/as/test/integration/web/formauth/resources/";
WebArchive war = ShrinkWrap.create(WebArchive.class, "form-auth.war");
war.setWebXML(tccl.getResource(resourcesLocation + "web.xml"));
war.addAsWebInfResource(tccl.getResource(resourcesLocation + "jboss-web.xml"), "jboss-web.xml");
war.addClass(SecureServlet.class);
war.addClass(SecuredPostServlet.class);
war.addClass(LogoutServlet.class);
war.addAsWebResource(tccl.getResource(resourcesLocation + "index.html"), "index.html");
war.addAsWebResource(tccl.getResource(resourcesLocation + "unsecure_form.html"), "unsecure_form.html");
war.addAsWebResource(tccl.getResource(resourcesLocation + "restricted/errors.jsp"), "restricted/errors.jsp");
war.addAsWebResource(tccl.getResource(resourcesLocation + "restricted/error.html"), "restricted/error.html");
war.addAsWebResource(tccl.getResource(resourcesLocation + "restricted/login.html"), "restricted/login.html");
return war;
}
/**
* Test form authentication of a secured servlet
*
* @throws Exception
*/
@Test
@OperateOnDeployment("form-auth.war")
public void testFormAuth() throws Exception {
log.trace("+++ testFormAuth");
doSecureGetWithLogin("restricted/SecuredServlet");
/*
* Access the resource without attempting a login to validate that the
* session is valid and that any caching on the server is working as
* expected.
*/
doSecureGet("restricted/SecuredServlet");
}
/**
* Test that a bad login is redirected to the errors.jsp and that the
* session j_exception is not null.
*/
@Test
@OperateOnDeployment("form-auth.war")
public void testFormAuthException() throws Exception {
log.trace("+++ testFormAuthException");
URL url = new URL(baseURLNoAuth + "restricted/SecuredServlet");
HttpGet httpget = new HttpGet(url.toURI());
log.trace("Executing request " + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
Header[] errorHeaders = response.getHeaders("X-NoJException");
assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
HttpEntity entity = response.getEntity();
if ((entity != null) && (entity.getContentLength() > 0)) {
String body = EntityUtils.toString(entity);
assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0);
} else {
fail("Empty body in response");
}
String sessionID = null;
for (Cookie k : httpclient.getCookieStore().getCookies()) {
if (k.getName().equalsIgnoreCase("JSESSIONID"))
sessionID = k.getValue();
}
log.trace("Saw JSESSIONID=" + sessionID);
// Submit the login form
HttpPost formPost = new HttpPost(baseURLNoAuth + "j_security_check");
formPost.addHeader("Referer", baseURLNoAuth + "restricted/login.html");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("j_username", "baduser"));
formparams.add(new BasicNameValuePair("j_password", "badpass"));
formPost.setEntity(new UrlEncodedFormEntity(formparams, StandardCharsets.UTF_8));
log.trace("Executing request " + formPost.getRequestLine());
HttpResponse postResponse = httpclient.execute(formPost);
statusCode = postResponse.getStatusLine().getStatusCode();
errorHeaders = postResponse.getHeaders("X-NoJException");
assertTrue("Should see HTTP_OK. Got " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is not null", errorHeaders.length != 0);
log.debug("Saw X-JException, " + Arrays.toString(errorHeaders));
}
/**
* Test form authentication of a secured servlet and validate that there is
* a SecurityAssociation setting Subject.
*/
@Test
@OperateOnDeployment("form-auth.war")
public void testFormAuthSubject() throws Exception {
log.trace("+++ testFormAuthSubject");
doSecureGetWithLogin("restricted/SecuredServlet");
}
/**
* Test that a post from an unsecured form to a secured servlet does not
* loose its data during the redirect to the form login.
*/
@Test
@OperateOnDeployment("form-auth.war")
public void testPostDataFormAuth() throws Exception {
log.trace("+++ testPostDataFormAuth");
URL url = new URL(baseURLNoAuth + "unsecure_form.html");
HttpGet httpget = new HttpGet(url.toURI());
log.trace("Executing request " + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
Header[] errorHeaders = response.getHeaders("X-NoJException");
assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
EntityUtils.consume(response.getEntity());
// Submit the form to /restricted/SecuredPostServlet
HttpPost restrictedPost = new HttpPost(baseURLNoAuth + "restricted/SecuredPostServlet");
List<NameValuePair> restrictedParams = new ArrayList<NameValuePair>();
restrictedParams.add(new BasicNameValuePair("checkParam", "123456"));
restrictedPost.setEntity(new UrlEncodedFormEntity(restrictedParams, StandardCharsets.UTF_8));
log.trace("Executing request " + restrictedPost.getRequestLine());
HttpResponse restrictedResponse = httpclient.execute(restrictedPost);
statusCode = restrictedResponse.getStatusLine().getStatusCode();
errorHeaders = restrictedResponse.getHeaders("X-NoJException");
assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
HttpEntity entity = restrictedResponse.getEntity();
if ((entity != null) && (entity.getContentLength() > 0)) {
String body = EntityUtils.toString(entity);
assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0);
} else {
fail("Empty body in response");
}
String sessionID = null;
for (Cookie k : httpclient.getCookieStore().getCookies()) {
if (k.getName().equalsIgnoreCase("JSESSIONID"))
sessionID = k.getValue();
}
log.trace("Saw JSESSIONID=" + sessionID);
// Submit the login form
HttpPost formPost = new HttpPost(baseURLNoAuth + "j_security_check");
formPost.addHeader("Referer", baseURLNoAuth + "restricted/login.html");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("j_username", "user1"));
formparams.add(new BasicNameValuePair("j_password", "password1"));
formPost.setEntity(new UrlEncodedFormEntity(formparams, StandardCharsets.UTF_8));
log.trace("Executing request " + formPost.getRequestLine());
HttpResponse postResponse = httpclient.execute(formPost);
statusCode = postResponse.getStatusLine().getStatusCode();
errorHeaders = postResponse.getHeaders("X-NoJException");
assertTrue("Should see HTTP_MOVED_TEMP. Got " + statusCode, statusCode == HttpURLConnection.HTTP_MOVED_TEMP);
assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
EntityUtils.consume(postResponse.getEntity());
// Follow the redirect to the SecureServlet
Header location = postResponse.getFirstHeader("Location");
URL indexURI = new URL(location.getValue());
HttpGet war1Index = new HttpGet(indexURI.toURI());
log.trace("Executing request " + war1Index.getRequestLine());
HttpResponse war1Response = httpclient.execute(war1Index);
statusCode = war1Response.getStatusLine().getStatusCode();
errorHeaders = war1Response.getHeaders("X-NoJException");
assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
HttpEntity war1Entity = war1Response.getEntity();
if ((war1Entity != null) && (entity.getContentLength() > 0)) {
String body = EntityUtils.toString(war1Entity);
if (body.indexOf("j_security_check") > 0)
fail("Get of " + indexURI + " redirected to login page");
} else {
fail("Empty body in response");
}
}
public HttpPost doSecureGetWithLogin(String path) throws Exception {
return doSecureGetWithLogin(path, USERNAME, PASSWORD);
}
public HttpPost doSecureGetWithLogin(String path, String username, String password) throws Exception {
log.trace("+++ doSecureGetWithLogin : " + path);
URL url = new URL(baseURLNoAuth + path);
HttpGet httpget = new HttpGet(url.toURI());
log.trace("Executing request " + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
Header[] errorHeaders = response.getHeaders("X-NoJException");
assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
HttpEntity entity = response.getEntity();
if ((entity != null) && (entity.getContentLength() > 0)) {
String body = EntityUtils.toString(entity);
assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0);
} else {
fail("Empty body in response");
}
String sessionID = null;
for (Cookie k : httpclient.getCookieStore().getCookies()) {
if (k.getName().equalsIgnoreCase("JSESSIONID"))
sessionID = k.getValue();
}
log.trace("Saw JSESSIONID=" + sessionID);
// Submit the login form
HttpPost formPost = new HttpPost(baseURLNoAuth + "j_security_check");
formPost.addHeader("Referer", baseURLNoAuth + "restricted/login.html");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("j_username", username));
formparams.add(new BasicNameValuePair("j_password", password));
formPost.setEntity(new UrlEncodedFormEntity(formparams, StandardCharsets.UTF_8));
log.trace("Executing request " + formPost.getRequestLine());
HttpResponse postResponse = httpclient.execute(formPost);
statusCode = postResponse.getStatusLine().getStatusCode();
errorHeaders = postResponse.getHeaders("X-NoJException");
assertTrue("Should see HTTP_MOVED_TEMP. Got " + statusCode, statusCode == HttpURLConnection.HTTP_MOVED_TEMP);
assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
EntityUtils.consume(postResponse.getEntity());
// Follow the redirect to the SecureServlet
Header location = postResponse.getFirstHeader("Location");
URL indexURI = new URL(location.getValue());
HttpGet war1Index = new HttpGet(url.toURI());
log.trace("Executing request " + war1Index.getRequestLine());
HttpResponse war1Response = httpclient.execute(war1Index);
statusCode = war1Response.getStatusLine().getStatusCode();
errorHeaders = war1Response.getHeaders("X-NoJException");
assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
HttpEntity war1Entity = war1Response.getEntity();
if ((war1Entity != null) && (entity.getContentLength() > 0)) {
String body = EntityUtils.toString(war1Entity);
if (body.indexOf("j_security_check") > 0)
fail("Get of " + indexURI + " redirected to login page");
} else {
fail("Empty body in response");
}
return formPost;
}
public void doSecureGet(String path) throws Exception {
log.trace("+++ doSecureGet : " + path);
String sessionID = null;
for (Cookie k : httpclient.getCookieStore().getCookies()) {
if (k.getName().equalsIgnoreCase("JSESSIONID"))
sessionID = k.getValue();
}
log.trace("Saw JSESSIONID=" + sessionID);
URL url = new URL(baseURLNoAuth + path);
HttpGet httpget = new HttpGet(url.toURI());
log.trace("Executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
Header[] errorHeaders = response.getHeaders("X-NoJException");
assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
}
}
| 16,941
| 44.178667
| 117
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/formauth/LogoutServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.formauth;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
/**
* A servlet that logs out a user by invalidating any current session and then
* redirects the user to the welcome page.
*
* @author Brian Stansberry
*/
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = -3011966217891889561L;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
response.sendRedirect(request.getContextPath() + "/index.html");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
}
| 2,308
| 38.810345
| 130
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/formauth/SecureServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.formauth;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.Principal;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
/**
* A servlet that is secured by the web.xml descriptor. When accessed it simply
* prints the getUserPrincipal that accessed the url.
*
* @author Scott.Stark@jboss.org
*/
public class SecureServlet extends HttpServlet {
private static final long serialVersionUID = -5805093391064514424L;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Principal user = request.getUserPrincipal();
HttpSession session = request.getSession(false);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>SecureServlet</title></head>");
out.println("<h1>SecureServlet Accessed</h1>");
out.println("<body>");
out.println("You have accessed this servlet as user:" + user);
if (session != null)
out.println("<br>The session id is: " + session.getId());
else
out.println("<br>There is no session");
out.println("</body></html>");
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
}
| 2,863
| 39.914286
| 130
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/formauth/SecuredPostServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.formauth;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.Principal;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* A secured servlet which is the target of a post from an unsecured servlet.
* This validates that the post data is not lost when the original post is
* redirected to the form auth login page.
*
* @author Scott.Stark@jboss.org
* @author lbarreiro@redhat.com
*/
public class SecuredPostServlet extends HttpServlet {
private static final long serialVersionUID = -1996243573114825441L;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
Principal user = request.getUserPrincipal();
String path = request.getPathInfo();
// Validate that there is an authenticated user
if (user == null)
throw new ServletException(path + " not secured");
// Validate that the original post data was not lost
String value = request.getParameter("checkParam");
if (value == null || value.equals("123456") == false)
throw new ServletException("Did not find checkParam=123456");
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<html>");
out.println("<head><title>" + path + "</title></head><body>");
out.println("<h1>" + path + " Accessed</h1>");
out.println("You have accessed this servlet as user: " + user);
out.println("</body></html>");
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
}
| 3,133
| 40.786667
| 122
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/listener/UnescapedURITestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.listener;
import java.net.Socket;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.client.helpers.Operations;
import org.jboss.as.test.integration.management.ManagementOperations;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.as.test.shared.SnapshotRestoreSetupTask;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import io.undertow.util.FileUtils;
@RunWith(Arquillian.class)
@ServerSetup(UnescapedURITestCase.Setup.class)
@RunAsClient
public class UnescapedURITestCase {
@ArquillianResource
private URI uri;
private static final int PORT = 7645;
private static final String NEWBINDING = "newbinding";
static class Setup extends SnapshotRestoreSetupTask {
@Override
public void doSetup(ManagementClient managementClient, String containerId) throws Exception {
ModelNode node = Operations.createAddOperation(PathAddress.parseCLIStyleAddress("/socket-binding-group=standard-sockets/socket-binding=" + NEWBINDING).toModelNode());
node.get("port").set(PORT);
ManagementOperations.executeOperation(managementClient.getControllerClient(), node);
node = Operations.createAddOperation(PathAddress.parseCLIStyleAddress("/subsystem=undertow/server=default-server/http-listener=newlistener").toModelNode());
node.get("socket-binding").set(NEWBINDING);
node.get("allow-unescaped-characters-in-url").set(true);
ManagementOperations.executeOperation(managementClient.getControllerClient(), node);
ServerReload.executeReloadAndWaitForCompletion(managementClient);
}
}
@Deployment
public static WebArchive deploy() {
return ShrinkWrap.create(WebArchive.class, "enctest.war")
.addClass(EchoServlet.class);
}
@Test
public void testForUnescapedCharacterInURLisRejected() throws Exception {
String res = getResult(uri.getPort());
Assert.assertTrue(res, res.startsWith("HTTP/1.1 400"));
Assert.assertFalse(res, res.contains("ECHO")); //we should not have hit the servlet
}
@Test
public void testForUnescapedCharacterInURLisAccepted() throws Exception {
String res = getResult(PORT);
Assert.assertTrue(res, res.startsWith("HTTP/1.1 200"));
Assert.assertTrue(res, res.contains("ECHO:/한 글"));
}
String getResult(int port) throws Exception {
try (Socket socket = new Socket(uri.getHost(), port)) {
socket.getOutputStream().write("GET /enctest/enc/한%20글 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".getBytes(StandardCharsets.UTF_8));
return FileUtils.readFile(socket.getInputStream());
}
}
}
| 4,356
| 39.719626
| 178
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/listener/EchoServlet.java
|
package org.jboss.as.test.integration.web.listener;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = "/enc/*")
public class EchoServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding(StandardCharsets.UTF_8.name());
resp.getWriter().write("ECHO:" + req.getPathInfo());
}
}
| 697
| 32.238095
| 113
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/multipart/defaultservlet/DefaultServletMultipartConfigTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.web.multipart.defaultservlet;
import static org.junit.Assert.assertEquals;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.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;
/**
* Tests that config applied to the default servlet is merged into its configuration
*
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
@RunAsClient
public class DefaultServletMultipartConfigTestCase {
public static final String MESSAGE = "A text part";
@ArquillianResource
protected URL url;
@Deployment
public static Archive<?> deploy2() throws Exception {
WebArchive jar = ShrinkWrap.create(WebArchive.class, "multipathTest.war");
jar.addClasses(MultipartFilter.class);
jar.addAsWebInfResource(DefaultServletMultipartConfigTestCase.class.getPackage(), "web.xml", "web.xml");
return jar;
}
@Test
public void testMultipartRequestToDefaultServlet() throws Exception {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost post = new HttpPost(url.toExternalForm() + "/servlet");
post.setEntity(MultipartEntityBuilder.create()
.addTextBody("file", MESSAGE)
.build());
HttpResponse response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
assertEquals(200, statusLine.getStatusCode());
String result = EntityUtils.toString(entity);
Assert.assertEquals(MESSAGE, result);
}
}
}
| 3,366
| 37.261364
| 112
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/web/multipart/defaultservlet/MultipartFilter.java
|
package org.jboss.as.test.integration.web.multipart.defaultservlet;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
/**
* @author Stuart Douglas
*/
@WebFilter( urlPatterns = "/*")
public class MultipartFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
Part part = req.getPart("file");
byte[] data = new byte[100];
int c;
InputStream inputStream = part.getInputStream();
while ((c = inputStream.read(data)) > 0) {
resp.getOutputStream().write(data, 0, c);
}
}
@Override
public void destroy() {
}
}
| 1,336
| 30.093023
| 132
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/jsp/JspTagTestCase.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.integration.jsp;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* See WFLY-2690
*/
@RunWith(Arquillian.class)
@RunAsClient
public class JspTagTestCase {
private static final String RESULT = "This is a header" + System.lineSeparator() +
System.lineSeparator() +
System.lineSeparator() +
"<div>tag</div>" + System.lineSeparator() +
System.lineSeparator() +
"Static content" + System.lineSeparator();
@Deployment
public static WebArchive deploy() {
return ShrinkWrap.create(WebArchive.class)
.addAsWebInfResource(JspTagTestCase.class.getPackage(), "web.xml", "web.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsWebInfResource(JspTagTestCase.class.getPackage(), "tag.tag", "tags/tag.tag")
.addAsWebResource(JspTagTestCase.class.getPackage(), "index.jsp", "index.jsp")
.addAsWebResource(JspTagTestCase.class.getPackage(), "index.jsp", "index2.jsp")
.addAsWebInfResource(JspTagTestCase.class.getPackage(), "header.jsp", "header.jsp");
}
@Test
public void test(@ArquillianResource URL url) throws Exception {
//we ignore line ending differences
Assert.assertEquals(RESULT.replace("\r", ""),HttpRequest.get(url + "index.jsp", 10, TimeUnit.SECONDS).replace("\r", ""));
Assert.assertEquals(RESULT.replace("\r", ""),HttpRequest.get(url + "index2.jsp", 10, TimeUnit.SECONDS).replace("\r", ""));
}
}
| 3,099
| 42.661972
| 130
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/ee/concurrent/DefaultContextServiceServletTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 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.integration.ee.concurrent;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.net.URL;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author Eduardo Martins
*/
@RunWith(Arquillian.class)
@RunAsClient
public class DefaultContextServiceServletTestCase {
@ArquillianResource
private URL url;
@Deployment
public static WebArchive deployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "war-example.war");
war.addClasses(HttpRequest.class, DefaultContextServiceTestServlet.class, TestServletRunnable.class);
war.addAsManifestResource(
createPermissionsXmlAsset(
// Needed for getting the principle and logging in in the DefaultContextServiceTestServlet
new RuntimePermission("org.jboss.security.*"),
// TODO (jrp) This permission needs to be removed once WFLY-4176 is resolved
new RuntimePermission("getClassLoader"),
new RuntimePermission("modifyThread"),
new RuntimePermission("getBootModuleLoader")
), "permissions.xml");
return war;
}
@Test
public void testServlet() throws Exception {
HttpRequest.get(url.toExternalForm() + "simple", 10, SECONDS);
}
}
| 2,893
| 39.760563
| 114
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/ee/concurrent/DefaultContextServiceTestServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 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.integration.ee.concurrent;
import jakarta.annotation.Resource;
import jakarta.enterprise.concurrent.ContextService;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Principal;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author Eduardo Martins
*/
@WebServlet(name = "SimpleServlet", urlPatterns = { "/simple" })
public class DefaultContextServiceTestServlet extends HttpServlet {
@Resource
private ContextService contextService;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.login("guest","guest");
Principal principal = req.getUserPrincipal();
String moduleName = null;
try {
moduleName = (String) new InitialContext().lookup("java:module/ModuleName");
} catch (NamingException e) {
throw new ServletException(e);
}
final Runnable runnable = new TestServletRunnable(moduleName);
final Runnable contextualProxy = contextService.createContextualProxy(runnable,Runnable.class);
final ExecutorService executorService = Executors.newSingleThreadExecutor();
try {
// WFLY-4308: test serialization of contextual proxies
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
final ObjectOutputStream stream = new ObjectOutputStream(bytes);
stream.writeObject(contextualProxy);
stream.close();
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
executorService.submit((Runnable) in.readObject()).get();
}
} catch (Throwable e) {
throw new ServletException(e);
} finally {
executorService.shutdown();
}
}
}
| 3,356
| 40.444444
| 113
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/ee/concurrent/TestServletRunnable.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.integration.ee.concurrent;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.io.Serializable;
/**
* @author Eduardo Martins
*/
public class TestServletRunnable implements Runnable, Serializable {
private final String moduleName;
public TestServletRunnable(String moduleName) {
this.moduleName = moduleName;
}
@Override
public void run() {
// asserts correct class loader is set
try {
Thread.currentThread().getContextClassLoader().loadClass(this.getClass().getName());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
// asserts correct naming context is set
final InitialContext initialContext;
try {
initialContext = new InitialContext();
} catch (NamingException e) {
throw new RuntimeException(e);
}
String moduleNameOnJNDI = null;
try {
moduleNameOnJNDI = (String) initialContext.lookup("java:module/ModuleName");
} catch (NamingException e) {
throw new RuntimeException(e);
}
if(!moduleName.equals(moduleNameOnJNDI)) {
throw new IllegalStateException("the module name " + moduleNameOnJNDI + " is not the expected " + moduleName);
}
}
}
| 2,391
| 35.242424
| 122
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/ee/naming/defaultbindings/concurrency/DefaultConcurrencyTestServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 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.integration.ee.naming.defaultbindings.concurrency;
import jakarta.annotation.Resource;
import jakarta.enterprise.concurrent.ContextService;
import jakarta.enterprise.concurrent.ManagedExecutorService;
import jakarta.enterprise.concurrent.ManagedScheduledExecutorService;
import jakarta.enterprise.concurrent.ManagedThreadFactory;
import javax.naming.InitialContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author Eduardo Martins
*/
@WebServlet(name = "SimpleServlet", urlPatterns = { "/simple" })
public class DefaultConcurrencyTestServlet extends HttpServlet {
@Resource
private ContextService contextService;
@Resource
private ManagedExecutorService managedExecutorService;
@Resource
private ManagedScheduledExecutorService managedScheduledExecutorService;
@Resource
private ManagedThreadFactory managedThreadFactory;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
// check injected resources
if(contextService == null) {
throw new NullPointerException("contextService");
}
if(managedExecutorService == null) {
throw new NullPointerException("managedExecutorService");
}
if(managedScheduledExecutorService == null) {
throw new NullPointerException("managedScheduledExecutorService");
}
if(managedThreadFactory == null) {
throw new NullPointerException("managedThreadFactory");
}
// checked jndi lookup
new InitialContext().lookup("java:comp/DefaultContextService");
new InitialContext().lookup("java:comp/DefaultManagedExecutorService");
new InitialContext().lookup("java:comp/DefaultManagedScheduledExecutorService");
new InitialContext().lookup("java:comp/DefaultManagedThreadFactory");
} catch (Throwable e) {
throw new ServletException(e);
}
}
}
| 3,326
| 39.573171
| 113
|
java
|
null |
wildfly-main/testsuite/integration/web/src/test/java/org/jboss/as/test/integration/ee/naming/defaultbindings/concurrency/DefaultConcurrencyServletTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 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.integration.ee.naming.defaultbindings.concurrency;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.net.URL;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* Test for EE's default data source on a Servlet
*
* @author Eduardo Martins
*/
@RunWith(Arquillian.class)
@RunAsClient
public class DefaultConcurrencyServletTestCase {
@ArquillianResource
private URL url;
@Deployment
public static WebArchive deployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, DefaultConcurrencyServletTestCase.class.getSimpleName()+".war");
war.addClasses(HttpRequest.class, DefaultConcurrencyTestServlet.class);
return war;
}
@Test
public void testServlet() throws Exception {
HttpRequest.get(url.toExternalForm() + "simple", 10, SECONDS);
}
}
| 2,267
| 35
| 125
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/package-info.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.
*/
/**
* This package contains a part of the AS integration testsuite, which checks permissions granted when running
* the AS with Java Security Manager (JSM) enabled.<br>
* <i>Permissions for jboss-modules are defined in src/test/config/security.policy</i>
*/
package org.jboss.as.testsuite.integration.secman;
| 1,338
| 43.633333
| 110
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/PermissionUtil.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.testsuite.integration.secman;
/**
* Helper class for permissions testing. This class is usually packaged to a library-like archive in a test deployment.
*
* @author Josef Cacek
*/
public class PermissionUtil {
/**
* Simply calls {@link System#getProperty(String)} method.
*
* @param property
* @return system property
*/
public static String getSystemProperty(String property) {
return System.getProperty(property);
}
}
| 1,516
| 35.119048
| 119
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/ForwardJSPTestCase.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.testsuite.integration.secman;
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.test.integration.security.common.Utils;
import org.jboss.as.testsuite.integration.secman.servlets.ForwardServlet;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.net.URI;
import java.net.URL;
import static org.junit.Assert.assertTrue;
/**
* Test that the servlet should be able to forward Jakarta Server Pages resource within same deployment.
*
* @author Lin Gao
*/
@RunWith(Arquillian.class)
public class ForwardJSPTestCase {
private static final String APP_NAME = "forward";
/**
* Creates archive with a tested application.
*
* @return {@link WebArchive} instance
*/
@Deployment(name = APP_NAME, testable = false)
public static WebArchive deployment() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, APP_NAME + ".war");
war.addClasses(ForwardServlet.class);
war.addAsWebResource(ForwardServlet.class.getPackage(), "forward.jsp", "forward.jsp");
return war;
}
@Test
public void testForwardResource(@ArquillianResource URL webAppURL) throws Exception {
final URI sysPropUri = new URI(webAppURL.toExternalForm() + ForwardServlet.SERVLET_PATH.substring(1));
final String respBody = Utils.makeCall(sysPropUri, 200);
assertTrue("jsp should be forwarded", respBody.contains("This is the forward.jsp"));
}
}
| 2,705
| 37.112676
| 110
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/subsystem/package-info.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.
*/
/**
* This package contains tests aimed to security-manager subsystem integration testing.
*/
package org.jboss.as.testsuite.integration.secman.subsystem;
| 1,182
| 41.25
| 87
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/subsystem/RemoveDeploymentPermissionsServerSetupTask.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.testsuite.integration.secman.subsystem;
import static org.junit.Assert.assertTrue;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.integration.management.util.CLIOpResult;
import org.jboss.as.test.integration.management.util.CLIWrapper;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.logging.Logger;
/**
* Setup task which removes <code>/subsystem=security-manager/deployment-permissions=default</code> node from the domain model.
* The {@link #tearDown(ManagementClient, String)} method restores the node with single attribute configured:<br/>
* <code>maximum-permissions=[{class=java.security.AllPermission}])</code>.
*
* @author Josef Cacek
*/
public class RemoveDeploymentPermissionsServerSetupTask implements ServerSetupTask {
private static CLIWrapper cli;
private static Logger LOGGER = Logger.getLogger(RemoveDeploymentPermissionsServerSetupTask.class);
/*
* (non-Javadoc)
*
* @see org.jboss.as.arquillian.api.ServerSetupTask#setup(org.jboss.as.arquillian.container.ManagementClient,
* java.lang.String)
*/
@Override
public final void setup(final ManagementClient managementClient, String containerId) throws Exception {
if (cli == null) {
cli = new CLIWrapper(true);
}
CLIOpResult result = null;
// remove the deployment permissions
cli.sendLine("/subsystem=security-manager/deployment-permissions=default:remove()");
result = cli.readAllAsOpResult();
assertTrue("Removing deployment-permissions by using management API failed", result.isIsOutcomeSuccess());
// reload the server
LOGGER.debug("Reloading the server");
reload(managementClient);
}
/*
* (non-Javadoc)
*
* @see org.jboss.as.arquillian.api.ServerSetupTask#tearDown(org.jboss.as.arquillian.container.ManagementClient,
* java.lang.String)
*/
@Override
public void tearDown(final ManagementClient managementClient, String containerId) throws Exception {
CLIOpResult result = null;
// remove the deployment permissions configuration if exists
cli.sendLine("/subsystem=security-manager/deployment-permissions=default:remove()", true);
result = cli.readAllAsOpResult();
LOGGER.debug("Just in case. We tried to remove deployment-permissions before adding it. Result of the delete: "
+ result.getFromResponse(ModelDescriptionConstants.OUTCOME));
// revert original deployment permissions
cli.sendLine(
"/subsystem=security-manager/deployment-permissions=default:add(maximum-permissions=[{class=java.security.AllPermission}])");
result = cli.readAllAsOpResult();
assertTrue("Reverting maximum-permissions by using management API failed", result.isIsOutcomeSuccess());
// reload the server
LOGGER.debug("Reloading the server");
reload(managementClient);
}
/**
* Provide reload operation on the server
*/
private static void reload(final ManagementClient managementClient) {
ServerReload.executeReloadAndWaitForCompletion(managementClient);
}
}
| 4,386
| 40
| 141
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/subsystem/ReloadableCliTestBase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.testsuite.integration.secman.subsystem;
import static org.junit.Assert.assertTrue;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.integration.management.base.AbstractCliTestBase;
import org.jboss.as.test.integration.management.util.CLIOpResult;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
/**
* Abstract parent for tests which needs to do CLI operations and reload the server.
*
* @author Josef Cacek
*/
public abstract class ReloadableCliTestBase extends AbstractCliTestBase {
private static Logger LOGGER = Logger.getLogger(ReloadableCliTestBase.class);
@ArquillianResource
private ManagementClient managementClient;
/**
* Executes given CLI operation and returns the result. It throws {@link AssertionError} if the operation fails.
*
* @param operation CLI operation
* @return operation result
* @throws Exception initialization of the CLI or results reading fails
*/
protected CLIOpResult doCliOperation(final String operation) throws Exception {
LOGGER.debugv("Performing CLI operation: {0}", operation);
initCLI();
cli.sendLine(operation);
return cli.readAllAsOpResult();
}
/**
* Executes given CLI operation and returns the result. It doesn't check if the operation finished without errors.
*
* @param operation CLI operation
* @return operation result
* @throws Exception initialization of the CLI or results reading fails
*/
protected CLIOpResult doCliOperationWithoutChecks(final String operation) throws Exception {
LOGGER.debugv("Performing CLI operation without checks: {0}", operation);
initCLI();
cli.sendLine(operation, true);
final CLIOpResult result = cli.readAllAsOpResult();
if (LOGGER.isDebugEnabled()) {
LOGGER.debugv("Operation result is: {0}", result.getResponseNode());
}
return result;
}
/**
* Executes server reload command and waits for completion.
*/
protected void reloadServer() {
ServerReload.executeReloadAndWaitForCompletion(managementClient);
}
/**
* Asserts that given operation result contains requirement for server reload.
*
* @param opResult
*/
protected void assertOperationRequiresReload(CLIOpResult opResult) {
final ModelNode responseNode = opResult.getResponseNode();
final String[] names = new String[] { "response-headers", "operation-requires-reload" };
assertTrue("Operation should require reload",
responseNode != null && responseNode.hasDefined(names) && responseNode.get(names).asBoolean());
}
}
| 3,866
| 38.060606
| 118
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/subsystem/MinimumPermissionsTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.testsuite.integration.secman.subsystem;
import java.net.URI;
import java.net.URL;
import jakarta.servlet.http.HttpServletResponse;
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.management.util.CLIOpResult;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.testsuite.integration.secman.servlets.PrintSystemPropertyServlet;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* This class contains test for minimum-permissions attribute in security-manager subsystem. The permissions listed in
* minimum-permissions should be granted to all deployed applications.
*
* @author Josef Cacek
*/
@RunWith(Arquillian.class)
@RunAsClient
public class MinimumPermissionsTestCase extends ReloadableCliTestBase {
private static final String DEPLOYMENT = "deployment";
private static Logger LOGGER = Logger.getLogger(MinimumPermissionsTestCase.class);
@ArquillianResource
private URL webAppURL;
/**
* Test deployment with {@link PrintSystemPropertyServlet} and without any permissions deployment descriptor.
*
* @return
*/
@Deployment(name = DEPLOYMENT, testable = false)
public static WebArchive deployment() {
LOGGER.debug("Start WAR deployment");
final WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT + ".war");
war.addClasses(PrintSystemPropertyServlet.class);
return war;
}
/**
* Tests that permissions are not granted if the minimum-permissions is empty.
*
* @throws Exception
*/
@Test
public void testEmptyMinPerm() throws Exception {
assertPropertyNonReadable();
}
/**
* Tests that property permissions are not granted if the minimum-permissions contains only a {@link java.io.FilePermission}
* entry.
*
* @throws Exception
*/
@Test
public void testFilePerm(@ArquillianResource URL webAppURL) throws Exception {
CLIOpResult opResult = doCliOperation(
"/subsystem=security-manager/deployment-permissions=default:write-attribute(name=minimum-permissions, value=[{class=java.io.FilePermission, actions=read, name=\"/-\"}])");
assertOperationRequiresReload(opResult);
reloadServer();
assertPropertyNonReadable();
opResult = doCliOperation(
"/subsystem=security-manager/deployment-permissions=default:undefine-attribute(name=minimum-permissions)");
assertOperationRequiresReload(opResult);
reloadServer();
}
/**
* Tests that permission for reading system property is granted if the minimum-permissions contains PropertyPermission with
* wildcard '*'. entry.
*
* @throws Exception
*/
@Test
public void testPropertyPerm(@ArquillianResource URL webAppURL) throws Exception {
doCliOperation(
"/subsystem=security-manager/deployment-permissions=default:write-attribute(name=minimum-permissions, value=[{class=java.util.PropertyPermission, actions=read, name=\"*\"}])");
reloadServer();
assertPropertyReadable();
doCliOperation(
"/subsystem=security-manager/deployment-permissions=default:undefine-attribute(name=minimum-permissions)");
reloadServer();
}
/**
* Tests that property permissions are granted if the minimum-permissions contains a {@link java.security.AllPermission}
* entry.
*
* @param webAppURL
* @throws Exception
*/
@Test
public void testAllPerm(@ArquillianResource URL webAppURL) throws Exception {
doCliOperation(
"/subsystem=security-manager/deployment-permissions=default:write-attribute(name=minimum-permissions, value=[{class=java.security.AllPermission}])");
reloadServer();
assertPropertyReadable();
doCliOperation(
"/subsystem=security-manager/deployment-permissions=default:undefine-attribute(name=minimum-permissions)");
reloadServer();
}
/**
* Checks access to a system property on the server using {@link PrintSystemPropertyServlet}.
*
* @param expectedCode expected HTTP Status code
* @throws Exception
*/
protected void checkPropertyAccess(boolean successExpected) throws Exception {
final String propertyName = "java.home";
final URI sysPropUri = new URI(webAppURL.toExternalForm() + PrintSystemPropertyServlet.SERVLET_PATH.substring(1) + "?"
+ Utils.encodeQueryParam(PrintSystemPropertyServlet.PARAM_PROPERTY_NAME, propertyName));
Utils.makeCall(sysPropUri, successExpected ? HttpServletResponse.SC_OK : HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
* Asserts that a system property is readable from the test deployment.
*
* @throws Exception
*/
protected void assertPropertyReadable() throws Exception {
checkPropertyAccess(true);
}
/**
* Asserts that a system property is not readable from the test deployment.
*
* @throws Exception
*/
protected void assertPropertyNonReadable() throws Exception {
checkPropertyAccess(false);
}
}
| 6,566
| 36.525714
| 192
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/subsystem/MaximumPermissionsTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.testsuite.integration.secman.subsystem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.net.URI;
import java.net.URL;
import java.util.PropertyPermission;
import jakarta.servlet.http.HttpServletResponse;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.integration.management.util.CLIOpResult;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.as.test.shared.integration.ejb.security.PermissionUtils;
import org.jboss.as.testsuite.integration.secman.servlets.PrintSystemPropertyServlet;
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.Test;
import org.junit.runner.RunWith;
/**
* This class contains test for maximum-permissions attribute in security-manager subsystem. The deployment should failed if the
* deployed application asks more permissions than is allowed by the maximum-permissions.
*
* @author Josef Cacek
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(RemoveDeploymentPermissionsServerSetupTask.class)
public class MaximumPermissionsTestCase extends ReloadableCliTestBase {
private static final String DEPLOYMENT_PERM = "deployment-perm";
private static final String DEPLOYMENT_JBOSS_PERM = "deployment-jboss-perm";
private static final String DEPLOYMENT_NO_PERM = "deployment-no-perm";
private static Logger LOGGER = Logger.getLogger(MaximumPermissionsTestCase.class);
private static final String ADDRESS_WEB = "http://" + TestSuiteEnvironment.getServerAddress() + ":8080/";
private static final String INDEX_HTML = "OK";
@ArquillianResource
private Deployer deployer;
/**
* Returns Arquillian deployment which defines requested permissions in permissions.xml.
*/
@Deployment(name = DEPLOYMENT_PERM, testable = false, managed = false)
public static WebArchive deploymentPerm() {
return createDeployment("permissions.xml", DEPLOYMENT_PERM);
}
/**
* Returns Arquillian deployment which defines requested permissions in jboss-permissions.xml.
*/
@Deployment(name = DEPLOYMENT_JBOSS_PERM, testable = false, managed = false)
public static WebArchive deploymentJBossPerm() {
return createDeployment("jboss-permissions.xml", DEPLOYMENT_JBOSS_PERM);
}
/**
* Returns Arquillian deployment which doesn't define requested permissions.
*/
@Deployment(name = DEPLOYMENT_NO_PERM, testable = false)
public static WebArchive deploymentNoPerm() {
return createDeployment(null, DEPLOYMENT_NO_PERM);
}
/**
* Tests if deployment fails
* <ul>
* <li>when maximum-permissions is not defined and {@code permissions.xml} requests some permissions;</li>
* <li>when maximum-permissions is not defined and {@code jboss-permissions.xml} requests some permissions.</li>
* </ul>
*/
@Test
public void testMaximumPermissionsEmpty() throws Exception {
try {
doCliOperation(
"/subsystem=security-manager/deployment-permissions=default:add(maximum-permissions=[])");
reloadServer();
assertNotDeployable(DEPLOYMENT_PERM);
assertNotDeployable(DEPLOYMENT_JBOSS_PERM);
} finally {
doCliOperationWithoutChecks("/subsystem=security-manager/deployment-permissions=default:remove()");
reloadServer();
}
}
/**
* Tests if deployment succeeds but doing protected action fails, when maximum-permissions is not defined and requested
* permissions declaration is not part of deployment.
*/
@Test
public void testNoPermEmptySet() throws Exception {
assertPropertyNonReadable(DEPLOYMENT_NO_PERM);
}
/**
* Tests if deployment fails, when maximum-permissions is contains another permissions than requested by deployment.
*/
@Test
public void testFilePerm(@ArquillianResource URL webAppURL) throws Exception {
try {
doCliOperation(
"/subsystem=security-manager/deployment-permissions=default:add(maximum-permissions=[{class=java.io.FilePermission, actions=read, name=\"/-\"}])");
reloadServer();
assertNotDeployable(DEPLOYMENT_PERM);
assertNotDeployable(DEPLOYMENT_JBOSS_PERM);
assertPropertyNonReadable(DEPLOYMENT_NO_PERM);
} finally {
doCliOperationWithoutChecks("/subsystem=security-manager/deployment-permissions=default:remove()");
reloadServer();
}
}
/**
* Tests if deployment succeeds and permissions are granted, when maximum-permissions is contains permissions requested by
* deployment.
*/
@Test
public void testPropertyPerm(@ArquillianResource URL webAppURL) throws Exception {
try {
CLIOpResult opResult = doCliOperation(
"/subsystem=security-manager/deployment-permissions=default:add(maximum-permissions=[{class=java.util.PropertyPermission, actions=read, name=\"*\"}])");
assertOperationRequiresReload(opResult);
reloadServer();
assertDeployable(DEPLOYMENT_PERM, true);
assertDeployable(DEPLOYMENT_JBOSS_PERM, true);
assertPropertyNonReadable(DEPLOYMENT_NO_PERM);
} finally {
CLIOpResult opResult = doCliOperationWithoutChecks("/subsystem=security-manager/deployment-permissions=default:remove()");
reloadServer();
assertOperationRequiresReload(opResult);
}
}
/**
* Tests if deployments succeeds and permissions are granted, when maximum-permissions contains AllPermission entry.
*/
@Test
public void testAllPermAndEmptySet(@ArquillianResource URL webAppURL) throws Exception {
try {
doCliOperation(
"/subsystem=security-manager/deployment-permissions=default:add(maximum-permissions=[{class=java.security.AllPermission}])");
reloadServer();
// check the test apps are deployable and they have requested permissions
try {
deployer.deploy(DEPLOYMENT_PERM);
assertPropertyReadable(DEPLOYMENT_PERM);
deployer.deploy(DEPLOYMENT_JBOSS_PERM);
assertPropertyReadable(DEPLOYMENT_JBOSS_PERM);
assertPropertyNonReadable(DEPLOYMENT_NO_PERM);
try {
// after removing permissions from maximum-set the deployment which requests non-granted permissions should
// fail.
CLIOpResult opResult = doCliOperation(
"/subsystem=security-manager/deployment-permissions=default:write-attribute(name=maximum-permissions, value=[]");
assertOperationRequiresReload(opResult);
reloadServer();
assertNotDeployed(DEPLOYMENT_PERM);
assertNotDeployed(DEPLOYMENT_JBOSS_PERM);
assertDeployed(DEPLOYMENT_NO_PERM);
} finally {
// clean-up - undeploy
CLIOpResult opResult = doCliOperation(
"/subsystem=security-manager/deployment-permissions=default:write-attribute(name=maximum-permissions, value=[{class=java.security.AllPermission}])");
reloadServer();
assertOperationRequiresReload(opResult);
}
} finally {
deployer.undeploy(DEPLOYMENT_PERM);
deployer.undeploy(DEPLOYMENT_JBOSS_PERM);
}
} finally {
CLIOpResult opResult = doCliOperationWithoutChecks("/subsystem=security-manager/deployment-permissions=default:remove()");
reloadServer();
assertOperationRequiresReload(opResult);
}
}
/**
* Checks access to a system property on the server using {@link PrintSystemPropertyServlet}.
*
* @param deploymentName
*
* @param expectedCode expected HTTP Status code
* @throws Exception
*/
protected void checkPropertyAccess(boolean successExpected, String deploymentName) throws Exception {
final String propertyName = "java.home";
final URI sysPropUri = new URI(ADDRESS_WEB + deploymentName + PrintSystemPropertyServlet.SERVLET_PATH + "?"
+ Utils.encodeQueryParam(PrintSystemPropertyServlet.PARAM_PROPERTY_NAME, propertyName));
Utils.makeCall(sysPropUri, successExpected ? HttpServletResponse.SC_OK : HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
* Asserts the system property is readable from deployment with given name.
*
* @param deploymentName
* @throws Exception
*/
protected void assertPropertyReadable(String deploymentName) throws Exception {
checkPropertyAccess(true, deploymentName);
}
/**
* Asserts the system property is not readable from deployment with given name.
*
* @param deploymentName
* @throws Exception
*/
protected void assertPropertyNonReadable(String deploymentName) throws Exception {
checkPropertyAccess(false, deploymentName);
}
/**
* Asserts the deployment of the application with given name succeeds and checks if system property is
* readable/non-readable.
*
* @param deploymentName
* @param expectedPropertyReadable expected "readability" of system property from deployment
* @throws Exception
*/
protected void assertDeployable(String deploymentName, boolean expectedPropertyReadable) throws Exception {
deployer.deploy(deploymentName);
LOGGER.debug("Manually deployed: " + deploymentName);
if (expectedPropertyReadable) {
assertPropertyReadable(deploymentName);
} else {
assertPropertyNonReadable(deploymentName);
}
deployer.undeploy(deploymentName);
}
/**
* Asserts the deployment of the application with given name fails.
*
* @param deploymentName
* @throws Exception
*/
protected void assertNotDeployable(String deploymentName) {
try {
deployer.deploy(deploymentName);
fail("Deployment failure expected for deployment: " + deploymentName);
} catch (Exception e) {
// expected
} finally {
try {
deployer.undeploy(deploymentName);
} catch (Exception e) {
LOGGER.debug(e);
}
}
}
/**
* Asserts the application with given name is deployed.
*
* @param deploymentName
* @throws Exception
*/
protected void assertDeployed(String deploymentName) throws Exception {
final URI sysPropUri = new URI(ADDRESS_WEB + deploymentName + "/");
final String strBody = Utils.makeCall(sysPropUri, HttpServletResponse.SC_OK);
assertEquals("Unexpected message body returned.", INDEX_HTML, strBody);
}
/**
* Asserts the application with given name is not-deployed.
*
* @param deploymentName
* @throws Exception
*/
protected void assertNotDeployed(String deploymentName) throws Exception {
final URI sysPropUri = new URI(ADDRESS_WEB + deploymentName + "/");
Utils.makeCall(sysPropUri, HttpServletResponse.SC_NOT_FOUND);
}
/**
* Creates deployment with {@link PrintSystemPropertyServlet} and index.html simple page. If permissionsFilename parameter
* is not-<code>null</code>, then permission declaration file with given name is also generated to the deployment.
*
* @param permissionsFilename filename under META-INF where to store requested permissions (usually permissions.xml,
* jboss-permissions.xml or null to skip requesting permissions)
* @param deploymentName
* @return
*/
private static WebArchive createDeployment(String permissionsFilename, String deploymentName) {
LOGGER.debug("Start WAR deployment");
final WebArchive war = ShrinkWrap.create(WebArchive.class, deploymentName + ".war");
war.addClasses(PrintSystemPropertyServlet.class);
war.addAsWebResource(new StringAsset(INDEX_HTML), "index.html");
if (permissionsFilename != null) {
war.addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(new PropertyPermission("*", "read")),
permissionsFilename);
}
return war;
}
}
| 14,051
| 40.329412
| 177
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/ejbs/ReadSystemPropertyBean.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.testsuite.integration.secman.ejbs;
import jakarta.ejb.Local;
import jakarta.ejb.Remote;
import jakarta.ejb.Stateless;
/**
* A SLSB bean which reads the given system property and returns its value.
*
* @author <a href="mailto:istudens@redhat.com">Ivo Studensky</a>
*/
@Stateless
@Remote(ReadSystemPropertyRemote.class)
@Local(ReadSystemPropertyLocal.class)
public class ReadSystemPropertyBean {
public String readSystemProperty(final String propertyName) {
return System.getProperty(propertyName, "");
}
}
| 1,571
| 37.341463
| 75
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/ejbs/ReadSystemPropertyRemote.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.testsuite.integration.secman.ejbs;
/**
* Remote interface dedicated for ReadSystemPropertyBean.
*
* @author <a href="mailto:istudens@redhat.com">Ivo Studensky</a>
*/
public interface ReadSystemPropertyRemote {
String readSystemProperty(final String propertyName);
}
| 1,319
| 40.25
| 70
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/ejbs/ReadSystemPropertyLocal.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.testsuite.integration.secman.ejbs;
/**
* Local interface dedicated for ReadSystemPropertyBean.
*
* @author <a href="mailto:istudens@redhat.com">Ivo Studensky</a>
*/
public interface ReadSystemPropertyLocal {
String readSystemProperty(final String propertyName);
}
| 1,317
| 40.1875
| 70
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/module/package-info.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.
*/
/**
* This package contains tests for permissions assigned to custom AS modules (<i>i.e. Permissions defined in module.xml</i>).
*/
package org.jboss.as.testsuite.integration.secman.module;
| 1,215
| 45.769231
| 125
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/module/GrantModulePermissionsTestCase.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.testsuite.integration.secman.module;
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.test.integration.security.common.Utils;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test case, which checks if full permissions set is used for an installed module when no <code><permissions></code>
* element is provided in module.xml.
*
* @author Josef Cacek
*/
@RunWith(Arquillian.class)
@ServerSetup(GrantModulePermissionsTestCase.CustomModuleSetup.class)
public class GrantModulePermissionsTestCase {
/**
* Creates test archive.
*
* @return test application
*/
@Deployment()
public static JavaArchive deployment() {
return ShrinkWrap
.create(JavaArchive.class, "modperm-grant.jar")
.addClass(AbstractCustomModuleServerSetup.class)
.addAsManifestResource(
Utils.getJBossDeploymentStructure(AbstractCustomModuleServerSetup.MODULE_NAME_BASE + ".grant"),
"jboss-deployment-structure.xml");
}
/**
* Test which reads system property.
*/
@Test
public void testReadJavaHome() {
CheckJSMUtils.getSystemProperty("java.home");
}
/**
* Test which checks a custom permission.
*/
@Test
public void testCustomPermission() {
CheckJSMUtils.checkRuntimePermission("org.jboss.security.Permission");
}
static class CustomModuleSetup extends AbstractCustomModuleServerSetup {
@Override
protected String getModuleSuffix() {
return "grant";
}
}
}
| 2,865
| 33.53012
| 123
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/module/DenyModulePermissionsTestCase.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.testsuite.integration.secman.module;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.security.AccessControlException;
import java.security.Permission;
import java.util.PropertyPermission;
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.test.integration.security.common.Utils;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test case, which checks if empty permissions set is used for an installed module when empty <code><permissions></code>
* element is provided in module.xml.
*
* @author Josef Cacek
*/
@RunWith(Arquillian.class)
@ServerSetup(DenyModulePermissionsTestCase.CustomModuleSetup.class)
public class DenyModulePermissionsTestCase {
/**
* Creates test archive.
*
* @return test application
*/
@Deployment()
public static JavaArchive deployment() {
return ShrinkWrap
.create(JavaArchive.class, "modperm-deny.jar")
.addClass(AbstractCustomModuleServerSetup.class)
.addAsManifestResource(
Utils.getJBossDeploymentStructure(AbstractCustomModuleServerSetup.MODULE_NAME_BASE + ".deny"),
"jboss-deployment-structure.xml");
}
/**
* Test which reads a system property.
*/
@Test
public void testReadJavaHome() {
try {
CheckJSMUtils.getSystemProperty("java.home");
fail("Access should be denied");
} catch (AccessControlException e) {
Permission expectedPerm = new PropertyPermission("java.home", "read");
assertEquals("Permission type doesn't match", expectedPerm, e.getPermission());
}
}
/**
* Test which checks a custom permission which should not be granted.
*/
@Test
public void testCustomPermission() {
final String permissionName = "org.jboss.security.Permission";
try {
CheckJSMUtils.checkRuntimePermission(permissionName);
fail("Access should be denied");
} catch (AccessControlException e) {
Permission expectedPerm = new RuntimePermission(permissionName);
assertEquals("Permission type doesn't match", expectedPerm, e.getPermission());
}
}
static class CustomModuleSetup extends AbstractCustomModuleServerSetup {
@Override
protected String getModuleSuffix() {
return "deny";
}
}
}
| 3,726
| 35.539216
| 127
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/module/AbstractCustomModuleServerSetup.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.testsuite.integration.secman.module;
import java.io.File;
import java.net.URISyntaxException;
import org.apache.commons.io.FileUtils;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.integration.management.util.CustomCLIExecutor;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
/**
* Server setup task base, which adds a custom module to the AS configuration. Child classes have to implement
* {@link #getModuleSuffix()} method, which is used to generate module name and to determine which descriptor file will be used
* as the final module.xml.
*
* @author Josef Cacek
*/
public abstract class AbstractCustomModuleServerSetup implements ServerSetupTask {
private static Logger LOGGER = Logger.getLogger(AbstractCustomModuleServerSetup.class);
public static final String MODULE_NAME_BASE = "org.jboss.test.secman";
private static final String MODULE_JAR = "modperm.jar";
private static final File WORK_DIR = new File("cust-module-test");
private static final File MODULE_JAR_FILE = new File(WORK_DIR, MODULE_JAR);
/**
* Creates work-directory where JAR containing {@link CheckJSMUtils} is stored. The JAR is then deployed as an AS module.
*/
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
LOGGER.trace("(Re)Creating workdir: " + WORK_DIR.getAbsolutePath());
FileUtils.deleteDirectory(WORK_DIR);
removeModule(getModuleSuffix());
WORK_DIR.mkdirs();
ShrinkWrap.create(JavaArchive.class, MODULE_JAR).addClass(CheckJSMUtils.class)
.as(org.jboss.shrinkwrap.api.exporter.ZipExporter.class).exportTo(MODULE_JAR_FILE, true);
addModule(getModuleSuffix());
}
/**
* Removes work-directory and removes the AS module.
*/
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
LOGGER.trace("Removing custom module");
FileUtils.deleteDirectory(WORK_DIR);
removeModule(getModuleSuffix());
}
/**
* Returns last part of module name. The name base is {@value #MODULE_NAME_BASE}
*/
protected abstract String getModuleSuffix();
private void addModule(String suffix) throws URISyntaxException {
File tmpFile = new File(getClass().getResource("module-" + suffix + ".xml").toURI());
CustomCLIExecutor.execute(null, "module add --name=" + MODULE_NAME_BASE + "." + suffix + " --resources="
+ escapePath(MODULE_JAR_FILE.getAbsolutePath()) + " --module-xml=" + escapePath(tmpFile.getAbsolutePath()));
}
private void removeModule(String suffix) throws URISyntaxException {
CustomCLIExecutor.execute(null, "module remove --name=" + MODULE_NAME_BASE + "." + suffix);
}
private String escapePath(final String str) {
return str == null ? null : str.replaceAll("([\\s])", "\\\\$1");
}
}
| 4,136
| 42.09375
| 127
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/module/LimitedModulePermissionsTestCase.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.testsuite.integration.secman.module;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.security.AccessControlException;
import java.security.Permission;
import java.util.PropertyPermission;
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.test.integration.security.common.Utils;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test case, which checks if limited permissions set defined in module.xml is used for an installed module.
*
* @author Josef Cacek
*/
@RunWith(Arquillian.class)
@ServerSetup(LimitedModulePermissionsTestCase.CustomModuleSetup.class)
public class LimitedModulePermissionsTestCase {
/**
* Creates test archive.
*
* @return test application
*/
@Deployment()
public static JavaArchive deployment() {
return ShrinkWrap
.create(JavaArchive.class, "modperm-limited.jar")
.addClass(AbstractCustomModuleServerSetup.class)
.addAsManifestResource(
Utils.getJBossDeploymentStructure(AbstractCustomModuleServerSetup.MODULE_NAME_BASE + ".limited"),
"jboss-deployment-structure.xml");
}
/**
* Test which reads system property without Permission.
*/
@Test
public void testReadJavaHome() {
try {
CheckJSMUtils.getSystemProperty("java.home");
fail("Access should be denied");
} catch (AccessControlException e) {
Permission expectedPerm = new PropertyPermission("java.home", "read");
assertEquals("Permission type doesn't match", expectedPerm, e.getPermission());
}
}
/**
* Test which checks custom permission which should not be granted.
*/
@Test
public void testCustomPermWithoutGrant() {
final String permissionName = "org.jboss.security.Permission";
try {
CheckJSMUtils.checkRuntimePermission(permissionName);
fail("Access should be denied");
} catch (AccessControlException e) {
Permission expectedPerm = new RuntimePermission(permissionName);
assertEquals("Permission type doesn't match", expectedPerm, e.getPermission());
}
}
/**
* Test which checks granted permission.
*/
@Test
public void testGrantedCustomPerm() {
CheckJSMUtils.checkRuntimePermission("secman.test.Permission");
}
static class CustomModuleSetup extends AbstractCustomModuleServerSetup {
@Override
protected String getModuleSuffix() {
return "limited";
}
}
}
| 3,898
| 34.445455
| 121
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/module/CheckJSMUtils.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.testsuite.integration.secman.module;
import java.security.AccessController;
import java.security.PrivilegedAction;
/**
* Utility class which will be placed in a custom module deployed to the AS. It has only limited set of permissions granted in
* its module.xml descriptor.
*
* @author Josef Cacek
*/
public class CheckJSMUtils {
public static String getSystemProperty(final String propName) throws IllegalStateException {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
return AccessController.doPrivileged(new PrivilegedAction<String>() {
@Override
public String run() {
return System.getProperty(propName);
}
});
}
throw new IllegalStateException("Java Security Manager is not initialized");
}
public static void checkRuntimePermission(final String permissionName) throws IllegalStateException {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
sm.checkPermission(new RuntimePermission(permissionName));
return null;
}
});
} else {
throw new IllegalStateException("Java Security Manager is not initialized");
}
}
}
| 2,505
| 37.553846
| 126
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/servlets/package-info.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 in which servlets checking JSM permissions are located.
*/
package org.jboss.as.testsuite.integration.secman.servlets;
| 1,158
| 43.576923
| 70
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/servlets/CallPermissionUtilServlet.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.testsuite.integration.secman.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jboss.as.testsuite.integration.secman.PermissionUtil;
/**
* Servlet which calls method(s) from {@link PermissionUtil} class usually packaged in a library (i.e. another archive).
*
* @author Josef Cacek
*/
@WebServlet(CallPermissionUtilServlet.SERVLET_PATH)
public class CallPermissionUtilServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String SERVLET_PATH = "/CallPermissionUtilServlet";
public static final String PARAM_PROPERTY_NAME = "property";
public static final String DEFAULT_PROPERTY_NAME = "java.home";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
String property = req.getParameter(PARAM_PROPERTY_NAME);
if (property == null || property.length() == 0) {
property = DEFAULT_PROPERTY_NAME;
}
final PrintWriter writer = resp.getWriter();
writer.write(PermissionUtil.getSystemProperty(property));
writer.close();
}
}
| 2,468
| 38.822581
| 120
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/servlets/JSMCheckServlet.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.testsuite.integration.secman.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Servlet, which checks if the Java Security Manager (JSM) is enabled. Response is a plain text "true" when JSM is enabled or
* "false" otherwise.
*
* @author Josef Cacek
*/
@WebServlet(JSMCheckServlet.SERVLET_PATH)
public class JSMCheckServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String SERVLET_PATH = "/JSMCheckServlet";
/**
* @param req
* @param resp
* @throws ServletException
* @throws IOException
* @see jakarta.servlet.http.HttpServlet#doGet(jakarta.servlet.http.HttpServletRequest, jakarta.servlet.http.HttpServletResponse)
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
final PrintWriter writer = resp.getWriter();
writer.write(Boolean.toString(System.getSecurityManager() != null));
writer.close();
}
}
| 2,345
| 36.83871
| 133
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/servlets/PrintSystemPropertyServlet.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.testsuite.integration.secman.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Servlet, which prints value of system property. By default it prints value of property {@value #DEFAULT_PROPERTY_NAME}, but
* you can specify another property name by using request parameter {@value #PARAM_PROPERTY_NAME}.
*
* @author Josef Cacek
*/
@WebServlet(PrintSystemPropertyServlet.SERVLET_PATH)
public class PrintSystemPropertyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String SERVLET_PATH = "/SysPropServlet";
public static final String PARAM_PROPERTY_NAME = "property";
public static final String DEFAULT_PROPERTY_NAME = "java.home";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
String property = req.getParameter(PARAM_PROPERTY_NAME);
if (property == null || property.length() == 0) {
property = DEFAULT_PROPERTY_NAME;
}
final PrintWriter writer = resp.getWriter();
writer.write(System.getProperty(property, ""));
writer.close();
}
}
| 2,488
| 39.803279
| 126
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/servlets/ForwardServlet.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.testsuite.integration.secman.servlets;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Servlet to check permissions granted to read resource within the same deployment.
*
* @author Lin Gao
*/
@WebServlet(ForwardServlet.SERVLET_PATH)
public class ForwardServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String SERVLET_PATH = "/Forward";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/forward.jsp");
dispatcher.forward(req,resp);
}
}
| 1,973
| 36.961538
| 113
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/propertypermission/PropertyPermissionExpressionsTestCase.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.testsuite.integration.secman.propertypermission;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.PropertyPermission;
import jakarta.servlet.http.HttpServletResponse;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.helpers.Operations;
import org.jboss.as.subsystem.test.SubsystemOperations;
import org.jboss.as.test.integration.security.common.AbstractSystemPropertiesServerSetupTask;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.as.test.shared.integration.ejb.security.PermissionUtils;
import org.jboss.as.testsuite.integration.secman.servlets.JSMCheckServlet;
import org.jboss.as.testsuite.integration.secman.servlets.PrintSystemPropertyServlet;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Verifies that enabling disabling spec-descriptor-property-replacement and jboss-descriptor-property-replacement on the EE subsystem the replacement via environment
* properties on permissions.xml and jboss-permissions.xml is enabled and disabled.
*
* @author Yeray Borges
*/
@RunAsClient
@RunWith(Arquillian.class)
@ServerSetup(PropertyPermissionExpressionsTestCase.SystemPropertiesSetup.class)
public class PropertyPermissionExpressionsTestCase {
private static final String PROPERTY_NAME = "ENVIRONMENT_PROP_NAME";
private static final String PROPERTY_VALUE = "java.home";
private static final PathAddress EE_SUBSYSTEM_PATH_ADDRESS = PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, "ee"));
private static final String VERIFY_JSM_DEPLOYMENT = "verify-jsm-deployment";
private static final String SPEC_PRINT_PROP_SERVLET_DEPLOYMENT = "spec_print-prop-servlet_deployment";
private static final String JBOSS_PRINT_PROP_SERVLET_DEPLOYMENT = "jboss_print-prop-servlet_deployment";
private static final Asset EXPRESSIONS_PERMISSIONS_XML = PermissionUtils.createPermissionsXmlAsset(new PropertyPermission(
"${"+PROPERTY_NAME+"}", "read"));
private ModelControllerClient client;
@ArquillianResource
private Deployer deployer;
@ArquillianResource
private ManagementClient mgmtClient;
@Deployment(name = VERIFY_JSM_DEPLOYMENT)
public static Archive<?> createJavaSecManagerVerifier() {
return ShrinkWrap.create(WebArchive.class, "verify-jsm-enabled.war")
.addClass(JSMCheckServlet.class);
}
@Deployment(name = SPEC_PRINT_PROP_SERVLET_DEPLOYMENT, managed = false, testable = false)
public static Archive<?> createSpectPrintPropServlet() {
return ShrinkWrap.create(WebArchive.class, SPEC_PRINT_PROP_SERVLET_DEPLOYMENT + ".war")
.addClass(PrintSystemPropertyServlet.class)
.addAsManifestResource(EXPRESSIONS_PERMISSIONS_XML, "permissions.xml");
}
@Deployment(name = JBOSS_PRINT_PROP_SERVLET_DEPLOYMENT, managed = false, testable = false)
public static Archive<?> createJbossPrintPropServlet() {
return ShrinkWrap.create(WebArchive.class, JBOSS_PRINT_PROP_SERVLET_DEPLOYMENT + ".war")
.addClass(PrintSystemPropertyServlet.class)
.addAsManifestResource(EXPRESSIONS_PERMISSIONS_XML, "jboss-permissions.xml");
}
@Test
@InSequence(10)
@OperateOnDeployment(VERIFY_JSM_DEPLOYMENT)
public void verifyJavaSecurityManageIsEnabled(@ArquillianResource() @OperateOnDeployment(VERIFY_JSM_DEPLOYMENT) URL webAppURL) throws Exception {
final URI checkJSMuri = new URI(webAppURL.toExternalForm() + JSMCheckServlet.SERVLET_PATH.substring(1));
assertEquals("JSM should be enabled.", Boolean.toString(true), Utils.makeCall(checkJSMuri, 200));
}
@Test
@InSequence(20)
public void verifyExpressionsInSpecPermissions() throws Exception {
verifyExpressionsInPermissions("spec-descriptor-property-replacement", SPEC_PRINT_PROP_SERVLET_DEPLOYMENT);
}
@Test
@InSequence(30)
public void verifyExpressionsInJbossPermissions() throws Exception {
verifyExpressionsInPermissions("jboss-descriptor-property-replacement", JBOSS_PRINT_PROP_SERVLET_DEPLOYMENT);
}
private void verifyExpressionsInPermissions(String eeSubsystemConfName, String deployment) throws Exception {
final URI sysPropUri = new URI(TestSuiteEnvironment.getHttpUrl() + "/" + deployment + "/" + PrintSystemPropertyServlet.SERVLET_PATH.substring(1));
client = mgmtClient.getControllerClient();
executeOperation(client, Operations.createWriteAttributeOperation(EE_SUBSYSTEM_PATH_ADDRESS.toModelNode(), eeSubsystemConfName, true));
deployer.deploy(deployment);
Utils.makeCall(sysPropUri, HttpServletResponse.SC_OK);
deployer.undeploy(deployment);
executeOperation(client, Operations.createWriteAttributeOperation(EE_SUBSYSTEM_PATH_ADDRESS.toModelNode(), eeSubsystemConfName, false));
deployer.deploy(deployment);
Utils.makeCall(sysPropUri, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
deployer.undeploy(deployment);
}
protected static ModelNode executeOperation(ModelControllerClient client, ModelNode op) throws IOException {
final ModelNode result = client.execute(op);
Assert.assertTrue(SubsystemOperations.getFailureDescriptionAsString(result), SubsystemOperations.isSuccessfulOutcome(result));
return result;
}
static class SystemPropertiesSetup extends AbstractSystemPropertiesServerSetupTask {
@Override
protected SystemProperty[] getSystemProperties() {
return new SystemProperty[] { new DefaultSystemProperty(PROPERTY_NAME, PROPERTY_VALUE) };
}
}
}
| 7,323
| 46.251613
| 166
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/propertypermission/WarPPTestCase.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.testsuite.integration.secman.propertypermission;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.net.URL;
import jakarta.servlet.http.HttpServletResponse;
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.testsuite.integration.secman.servlets.PrintSystemPropertyServlet;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
/**
* Test case, which checks PropertyPermissions assigned to deployed web applications. The applications try to do a protected
* action and it should either complete successfully if {@link java.util.PropertyPermission} is granted, or fail.
*
* @author Josef Cacek
*/
@RunWith(Arquillian.class)
@ServerSetup(SystemPropertiesSetup.class)
@RunAsClient
public class WarPPTestCase extends AbstractPPTestsWithJSP {
private static Logger LOGGER = Logger.getLogger(WarPPTestCase.class);
/**
* Creates archive with a tested application.
*
* @return {@link WebArchive} instance
*/
@Deployment(name = APP_GRANT, testable = false)
public static WebArchive grantDeployment() {
return warDeployment(APP_GRANT, GRANT_PERMISSIONS_XML);
}
/**
* Creates archive with a tested application.
*
* @return {@link WebArchive} instance
*/
@Deployment(name = APP_LIMITED, testable = false)
public static WebArchive limitedDeployment() {
return warDeployment(APP_LIMITED, LIMITED_PERMISSIONS_XML);
}
/**
* Creates archive with a tested application.
*
* @return {@link WebArchive} instance
*/
@Deployment(name = APP_DENY, testable = false)
public static WebArchive denyDeployment() {
return warDeployment(APP_DENY, EMPTY_PERMISSIONS_XML);
}
private static WebArchive warDeployment(final String appName, Asset permissionsXmlAsset) {
LOGGER.trace("Start WAR deployment");
final WebArchive war = ShrinkWrap.create(WebArchive.class, appName + ".war");
addJSMCheckServlet(war);
addPermissionsXml(war, permissionsXmlAsset, null);
war.addClasses(PrintSystemPropertyServlet.class);
war.addAsWebResource(PrintSystemPropertyServlet.class.getPackage(), "readproperty.jsp", "readproperty.jsp");
return war;
}
/**
* Checks access to a system property on the server using {@link PrintSystemPropertyServlet}.
*
* @param webAppURL
* @param propertyName
* @param expectedCode expected HTTP Status code
* @param expectedBody expected response value; if null then response body is not checked
* @throws Exception
*/
@Override
protected void checkProperty(final URL webAppURL, final String propertyName, final int expectedCode,
final String expectedBody) throws Exception {
final URI sysPropUri = new URI(webAppURL.toExternalForm() + PrintSystemPropertyServlet.SERVLET_PATH.substring(1) + "?"
+ Utils.encodeQueryParam(PrintSystemPropertyServlet.PARAM_PROPERTY_NAME, propertyName));
LOGGER.debug("Checking if '" + propertyName + "' property is available: " + sysPropUri);
final String respBody = Utils.makeCall(sysPropUri, expectedCode);
if (expectedBody != null && HttpServletResponse.SC_OK == expectedCode) {
assertEquals("System property value doesn't match the expected one.", expectedBody, respBody);
}
}
/**
* Checks access to a system property on the server using <code>readproperty.jsp</code>.
*
* @param webAppURL
* @param propertyName
* @param expectedCode expected HTTP Status code
* @param expectedBodyStart expected beginning of response value; if null then response body is not checked
* @throws Exception
*/
@Override
protected void checkPropertyInJSP(final URL webAppURL, final String propertyName, final int expectedCode,
final String expectedBodyStart) throws Exception {
final URI sysPropUri = new URI(webAppURL.toExternalForm() + "readproperty.jsp" + "?"
+ Utils.encodeQueryParam(PrintSystemPropertyServlet.PARAM_PROPERTY_NAME, propertyName));
LOGGER.debug("Checking if '" + propertyName + "' property is available: " + sysPropUri);
final String respBody = Utils.makeCall(sysPropUri, expectedCode);
if (expectedBodyStart != null && HttpServletResponse.SC_OK == expectedCode) {
assertNotNull("Response from JSP should not be null.", respBody);
assertTrue("The readproperty.jsp response doesn't start with the expected value.",
respBody.startsWith(expectedBodyStart));
}
}
}
| 6,149
| 41.708333
| 126
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/propertypermission/package-info.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.
*/
/**
* This package contains tests related to granting java.util.PropertyPermission in AS deployments.
* <i>Permissions for the deployments are defined in permissions.xml and/or jboss-permissions.xml</i>
*/
package org.jboss.as.testsuite.integration.secman.propertypermission;
| 1,304
| 44
| 101
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/propertypermission/EarModulesPPTestCase.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.testsuite.integration.secman.propertypermission;
import static org.jboss.as.testsuite.integration.secman.propertypermission.SystemPropertiesSetup.PROPERTY_NAME;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.net.URI;
import java.net.URL;
import java.security.AccessControlException;
import jakarta.ejb.EJBException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jakarta.servlet.http.HttpServletResponse;
import org.hamcrest.CoreMatchers;
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.Utils;
import org.jboss.as.testsuite.integration.secman.ejbs.ReadSystemPropertyBean;
import org.jboss.as.testsuite.integration.secman.ejbs.ReadSystemPropertyRemote;
import org.jboss.as.testsuite.integration.secman.servlets.PrintSystemPropertyServlet;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test case, which checks PropertyPermissions assigned to sub-deployment of deployed ear applications. The applications try to
* do a protected action and it should either complete successfully if {@link java.util.PropertyPermission} is granted, or fail.
*
* @author Ondrej Lukas
* @author Josef Cacek
*/
@RunWith(Arquillian.class)
@ServerSetup(SystemPropertiesSetup.class)
@RunAsClient
public class EarModulesPPTestCase extends AbstractPPTestsWithJSP {
private static final String EJBAPP_BASE_NAME = "ejb-module";
private static final String WEBAPP_BASE_NAME = "web-module";
private static final String APP_NO_PERM = "read-props-noperm";
private static final String APP_EMPTY_PERM = "read-props-emptyperm";
private static Logger LOGGER = Logger.getLogger(EarModulesPPTestCase.class);
@ArquillianResource
private InitialContext iniCtx;
/**
* Creates archive with a tested application.
*
* @return {@link EnterpriseArchive} instance
*/
@Deployment(name = APP_GRANT, testable = false)
public static EnterpriseArchive createDeployment1() {
return earDeployment(APP_GRANT, AbstractPropertyPermissionTests.GRANT_PERMISSIONS_XML);
}
/**
* Creates archive with a tested application.
*
* @return {@link EnterpriseArchive} instance
*/
@Deployment(name = APP_LIMITED, testable = false)
public static EnterpriseArchive createDeployment2() {
return earDeployment(APP_LIMITED, AbstractPropertyPermissionTests.LIMITED_PERMISSIONS_XML);
}
/**
* Creates archive with a tested application.
*
* @return {@link EnterpriseArchive} instance
*/
@Deployment(name = APP_DENY, testable = false)
public static EnterpriseArchive createDeployment3() {
return earDeployment(APP_DENY, AbstractPropertyPermissionTests.EMPTY_PERMISSIONS_XML);
}
/**
* Creates archive with a tested application.
*
* @return {@link EnterpriseArchive} instance
*/
@Deployment(name = APP_NO_PERM, testable = false)
public static EnterpriseArchive createNoPermDeployment() {
return earDeployment(APP_NO_PERM, null, ALL_PERMISSIONS_XML);
}
/**
* Creates archive with a tested application.
*
* @return {@link EnterpriseArchive} instance
*/
@Deployment(name = APP_EMPTY_PERM, testable = false)
public static EnterpriseArchive createEmptyPermDeployment() {
return earDeployment(APP_EMPTY_PERM, AbstractPropertyPermissionTests.EMPTY_PERMISSIONS_XML, ALL_PERMISSIONS_XML);
}
/**
* Check standard java property access for Jakarta Enterprise Beans in ear, where PropertyPermission for all properties is granted.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_GRANT)
public void testJavaHomePropertyEjbInJarGrant() throws Exception {
checkJavaHomePropertyEjb(APP_GRANT, false);
}
/**
* Check standard java property access for Jakarta Enterprise Beans in ear, where not all PropertyPermissions are granted.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_LIMITED)
public void testJavaHomePropertyEjbInJarLimited() throws Exception {
checkJavaHomePropertyEjb(APP_LIMITED, false);
}
/**
* Check standard java property access for Jakarta Enterprise Beans in ear, where no PropertyPermission is granted.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_DENY)
public void testJavaHomePropertyEjbInJarDeny() throws Exception {
checkJavaHomePropertyEjb(APP_DENY, true);
}
/**
* Check standard java property access for Jakarta Enterprise Beans in ear, where PropertyPermission for all properties is granted.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_GRANT)
public void testASLevelPropertyEjbInJarGrant() throws Exception {
checkTestPropertyEjb(APP_GRANT, false);
}
/**
* Check standard java property access for Jakarta Enterprise Beans in ear, where not all PropertyPermissions are granted.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_LIMITED)
public void testASLevelPropertyEjbInJarLimited() throws Exception {
checkTestPropertyEjb(APP_LIMITED, true);
}
/**
* Check standard java property access for Jakarta Enterprise Beans in ear, where no PropertyPermission is granted.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_DENY)
public void testASLevelPropertyEjbInJarDeny() throws Exception {
checkTestPropertyEjb(APP_DENY, true);
}
/**
* Check permission.xml overrides in ear deployments.
*/
@Test
@OperateOnDeployment(APP_NO_PERM)
public void testASLevelPropertyEjbInJarNoPerm() throws Exception {
checkTestPropertyEjb(APP_NO_PERM, true);
}
/**
* Check permission.xml overrides in ear deployments.
*/
@Test
@OperateOnDeployment(APP_EMPTY_PERM)
public void testASLevelPropertyEjbInJarEmptyPerm() throws Exception {
checkTestPropertyEjb(APP_EMPTY_PERM, true);
}
/**
* Check permission.xml overrides in ear deployments.
*/
@Test
@OperateOnDeployment(APP_NO_PERM)
public void testJavaHomePropertyInJSPNoPerm(@ArquillianResource URL webAppURL) throws Exception {
checkJavaHomePropertyInJSP(webAppURL, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
* Check permission.xml overrides in ear deployments.
*/
@Test
@OperateOnDeployment(APP_EMPTY_PERM)
public void testJavaHomePropertyInJSPEmptyPerm(@ArquillianResource URL webAppURL) throws Exception {
checkJavaHomePropertyInJSP(webAppURL, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
* Check permission.xml overrides in ear deployments.
*/
@Test
@OperateOnDeployment(APP_NO_PERM)
public void testASLevelPropertyInJSPNoPerm(@ArquillianResource URL webAppURL) throws Exception {
checkTestPropertyInJSP(webAppURL, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
* Check permission.xml overrides in ear deployments.
*/
@Test
@OperateOnDeployment(APP_EMPTY_PERM)
public void testASLevelPropertyInJSPEmptyPerm(@ArquillianResource URL webAppURL) throws Exception {
checkTestPropertyInJSP(webAppURL, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
* Check permission.xml overrides in ear deployments.
*/
@Test
@OperateOnDeployment(APP_NO_PERM)
public void testASLevelPropertyNoPerm(@ArquillianResource URL webAppURL) throws Exception {
checkTestProperty(webAppURL, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
* Check permission.xml overrides in ear deployments.
*/
@Test
@OperateOnDeployment(APP_EMPTY_PERM)
public void testASLevelPropertyEmptyPerm(@ArquillianResource URL webAppURL) throws Exception {
checkTestProperty(webAppURL, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
* Check access to 'java.home' property.
*/
private void checkJavaHomePropertyEjb(final String moduleNameSuffix, final boolean exceptionExpected) throws Exception {
checkPropertyEjb(moduleNameSuffix, "java.home", exceptionExpected, null);
}
/**
* Check access to {@value #EARAPP_BASE_NAME} property.
*/
private void checkTestPropertyEjb(final String moduleNameSuffix, final boolean exceptionExpected) throws Exception {
checkPropertyEjb(moduleNameSuffix, PROPERTY_NAME, exceptionExpected, PROPERTY_NAME);
}
/**
* Checks access to a system property on the server using {@link PrintSystemPropertyServlet}.
*
* @param webAppURL
* @param propertyName
* @param expectedCode expected HTTP Status code
* @param expectedBody expected response value; if null then response body is not checked
* @throws Exception
*/
@Override
protected void checkProperty(final URL webAppURL, final String propertyName, final int expectedCode,
final String expectedBody) throws Exception {
final URI sysPropUri = new URI(webAppURL.toExternalForm() + PrintSystemPropertyServlet.SERVLET_PATH.substring(1) + "?"
+ Utils.encodeQueryParam(PrintSystemPropertyServlet.PARAM_PROPERTY_NAME, propertyName));
LOGGER.debug("Checking if '" + propertyName + "' property is available: " + sysPropUri);
final String respBody = Utils.makeCall(sysPropUri, expectedCode);
if (expectedBody != null && HttpServletResponse.SC_OK == expectedCode) {
assertThat("System property value doesn't match the expected one.", respBody,
CoreMatchers.containsString(expectedBody));
}
}
/**
* Checks access to a system property on the server using <code>readproperty.jsp</code>.
*
* @param webAppURL
* @param propertyName
* @param expectedCode expected HTTP Status code
* @param expectedBodyStart expected beginning of response value; if null then response body is not checked
* @throws Exception
*/
@Override
protected void checkPropertyInJSP(final URL webAppURL, final String propertyName, final int expectedCode,
final String expectedBodyStart) throws Exception {
final URI sysPropUri = new URI(webAppURL.toExternalForm() + "readproperty.jsp" + "?"
+ Utils.encodeQueryParam(PrintSystemPropertyServlet.PARAM_PROPERTY_NAME, propertyName));
LOGGER.debug("Checking if '" + propertyName + "' property is available: " + sysPropUri);
final String respBody = Utils.makeCall(sysPropUri, expectedCode);
if (expectedBodyStart != null && HttpServletResponse.SC_OK == expectedCode) {
assertNotNull("Response from JSP should not be null.", respBody);
assertTrue("The readproperty.jsp response doesn't start with the expected value.",
respBody.startsWith(expectedBodyStart));
}
}
/**
* Checks access to a system property on the server using Jakarta Enterprise Beans.
*
* @param moduleName
* @param propertyName
* @param exceptionExpected
* @param expectedValue
* @throws Exception
*/
private void checkPropertyEjb(final String moduleName, final String propertyName, final boolean exceptionExpected,
final String expectedValue) throws Exception {
LOGGER.debug("Checking if '" + propertyName + "' property is available");
ReadSystemPropertyRemote bean = lookupEjb(moduleName, EJBAPP_BASE_NAME + moduleName,
ReadSystemPropertyBean.class.getSimpleName(), ReadSystemPropertyRemote.class);
assertNotNull(bean);
Exception ex = null;
String propertyValue = null;
try {
propertyValue = bean.readSystemProperty(propertyName);
} catch (Exception e) {
ex = e;
}
if (ex instanceof EJBException && ex.getCause() instanceof AccessControlException) {
assertTrue("AccessControlException came, but it was not expected", exceptionExpected);
} else if (ex != null) {
throw ex;
} else if (exceptionExpected) {
fail("AccessControlException was expected");
}
if (ex == null && expectedValue != null) {
assertEquals("System property value doesn't match the expected one.", expectedValue, propertyValue);
}
}
private <T> T lookupEjb(final String appName, final String moduleName, final String beanName, final Class<T> interfaceType)
throws NamingException {
return interfaceType.cast(iniCtx.lookup("ejb:" + appName + "/" + moduleName + "//" + beanName + "!"
+ interfaceType.getName()));
}
private static EnterpriseArchive earDeployment(final String suffix, final Asset permissionsXml) {
return earDeployment(suffix, permissionsXml, null);
}
private static EnterpriseArchive earDeployment(final String suffix, final Asset permissionsXml, final Asset modulesPermXml) {
JavaArchive jar = ejbDeployment(suffix);
WebArchive war = warDeployment(suffix);
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, suffix + ".ear");
addPermissionsXml(jar, modulesPermXml, null);
addPermissionsXml(war, modulesPermXml, null);
ear.addAsModule(jar);
ear.addAsModule(war);
addPermissionsXml(ear, permissionsXml, null);
return ear;
}
private static JavaArchive ejbDeployment(final String suffix) {
final JavaArchive ejb = ShrinkWrap.create(JavaArchive.class, EJBAPP_BASE_NAME + suffix + ".jar");
ejb.addPackage(ReadSystemPropertyBean.class.getPackage());
return ejb;
}
private static WebArchive warDeployment(final String suffix) {
final WebArchive war = ShrinkWrap.create(WebArchive.class, WEBAPP_BASE_NAME + suffix + ".war");
war.addClasses(PrintSystemPropertyServlet.class);
war.addAsWebResource(PrintSystemPropertyServlet.class.getPackage(), "readproperty.jsp", "readproperty.jsp");
addJSMCheckServlet(war);
return war;
}
}
| 16,155
| 38.309002
| 135
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/propertypermission/PermissionParserExpressionsTestCase.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.testsuite.integration.secman.propertypermission;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FilePermission;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.Permission;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Pattern;
import javax.xml.stream.XMLInputFactory;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.module.ExpressionStreamReaderDelegate;
import org.jboss.metadata.property.CompositePropertyResolver;
import org.jboss.metadata.property.PropertyReplacer;
import org.jboss.metadata.property.PropertyReplacers;
import org.jboss.metadata.property.SimpleExpressionResolver;
import org.jboss.metadata.property.SystemPropertyResolver;
import org.jboss.modules.LocalModuleLoader;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoader;
import org.jboss.modules.security.PermissionFactory;
import org.junit.Assert;
import org.junit.Test;
import org.wildfly.extension.security.manager.deployment.PermissionsParser;
/**
* Unit test to verify that the permissions parser is able to use a property resolver to parse permissions.
*
* @author Yeray Borges
*/
public class PermissionParserExpressionsTestCase {
final List<SimpleExpressionResolver> resolvers = Arrays.asList(SystemPropertyResolver.INSTANCE);
final CompositePropertyResolver compositePropertyResolver = new CompositePropertyResolver(resolvers.toArray(new SimpleExpressionResolver[0]));
final PropertyReplacer propertyReplacer = PropertyReplacers.resolvingExpressionReplacer(compositePropertyResolver);
final ModuleIdentifier identifier = ModuleIdentifier.fromString("java.base");
final Path fileUnderTest = Paths.get("src", "test", "resources", "propertypermission", "permissions.xml");
final Function<String, String> functionExpand = (value) -> propertyReplacer.replaceProperties(value);
@Test
public void test() throws DeploymentUnitProcessingException {
System.setProperty("CLASS_NAME", "java.io.FilePermission");
System.setProperty("NAME_A", "A");
System.setProperty("NAME_B", "B");
System.setProperty("NAME_C", "C");
System.setProperty("ACTION_READ", "read");
File[] modulePaths = getModulePaths();
LocalModuleLoader ml = new LocalModuleLoader(modulePaths);
List<PermissionFactory> permissionFactories = parsePermissions(fileUnderTest, ml, identifier, functionExpand);
Assert.assertEquals("Unexpected number of permissions", 3, permissionFactories.size());
Permission permission = permissionFactories.get(0).construct();
Assert.assertNotNull(permission);
Assert.assertTrue("Unexpected permission class", permission instanceof FilePermission);
Assert.assertEquals("Unexpected permission name", permission.getName(), "A");
Assert.assertEquals("Unexpected permission action", permission.getActions(), "read");
permission = permissionFactories.get(1).construct();
Assert.assertNotNull(permission);
Assert.assertTrue("Unexpected permission class", permission instanceof FilePermission);
Assert.assertEquals("Unexpected permission name", permission.getName(), "B");
Assert.assertEquals("Unexpected permission action", permission.getActions(), "read");
permission = permissionFactories.get(2).construct();
Assert.assertNotNull(permission);
Assert.assertTrue("Unexpected permission class", permission instanceof FilePermission);
Assert.assertEquals("Unexpected permission name", permission.getName(), "C");
Assert.assertEquals("Unexpected permission action", permission.getActions(), "write");
}
private List<PermissionFactory> parsePermissions(final Path path, final ModuleLoader loader, final ModuleIdentifier identifier, final Function<String, String> exprExpandFunction)
throws DeploymentUnitProcessingException {
InputStream inputStream = null;
try {
inputStream = Files.newInputStream(path);
final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
final ExpressionStreamReaderDelegate expressionStreamReaderDelegate = new ExpressionStreamReaderDelegate(inputFactory.createXMLStreamReader(inputStream), exprExpandFunction);
return PermissionsParser.parse(expressionStreamReaderDelegate, loader, identifier);
} catch (Exception e) {
throw new DeploymentUnitProcessingException(e.getMessage(), e);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
}
}
}
private File[] getModulePaths() {
final List<File> files = new ArrayList<>();
String modulePath = System.getProperty("module.path");
if (modulePath == null) {
fail("module.path system property is not set");
}
final String[] modulePaths = modulePath.split(Pattern.quote(File.pathSeparator));
for (String path: modulePaths) {
files.add(Paths.get(path).normalize().toFile());
}
return files.toArray(new File[]{});
}
}
| 6,076
| 44.014815
| 186
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/propertypermission/EarLibInWarPPTestCase.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.testsuite.integration.secman.propertypermission;
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.testsuite.integration.secman.servlets.CallPermissionUtilServlet;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
/**
* Test case, which checks PropertyPermissions assigned to lib in war of deployed ear applications. The applications try to do a
* protected action and it should either complete successfully if {@link java.util.PropertyPermission} is granted, or fail.
*
* @author Ondrej Lukas
* @author Josef Cacek
*/
@RunWith(Arquillian.class)
@ServerSetup(SystemPropertiesSetup.class)
@RunAsClient
public class EarLibInWarPPTestCase extends AbstractPPTestsWithLibrary {
/**
* Creates archive with a tested application.
*
* @return {@link EnterpriseArchive} instance
*/
@Deployment(name = APP_GRANT, testable = false)
public static EnterpriseArchive createDeployment1() {
return earDeployment(APP_GRANT, GRANT_PERMISSIONS_XML);
}
/**
* Creates archive with a tested application.
*
* @return {@link EnterpriseArchive} instance
*/
@Deployment(name = APP_LIMITED, testable = false)
public static EnterpriseArchive createDeployment2() {
return earDeployment(APP_LIMITED, LIMITED_PERMISSIONS_XML);
}
/**
* Creates archive with a tested application.
*
* @return {@link EnterpriseArchive} instance
*/
@Deployment(name = APP_DENY, testable = false)
public static EnterpriseArchive createDeployment3() {
return earDeployment(APP_DENY, EMPTY_PERMISSIONS_XML);
}
private static EnterpriseArchive earDeployment(final String app, Asset permissionsXml) {
final WebArchive war = ShrinkWrap.create(WebArchive.class, app + ".war");
addJSMCheckServlet(war);
war.addClasses(CallPermissionUtilServlet.class);
war.addAsLibraries(createLibrary());
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, app + ".ear");
// override grant-all in permissions.xml by customized jboss-permissions.xm
addPermissionsXml(ear, ALL_PERMISSIONS_XML, permissionsXml);
ear.addAsModule(war);
return ear;
}
}
| 3,623
| 37.967742
| 128
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/propertypermission/AbstractPPTestsWithLibrary.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.testsuite.integration.secman.propertypermission;
import static org.junit.Assert.assertEquals;
import java.net.URI;
import java.net.URL;
import jakarta.servlet.http.HttpServletResponse;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.testsuite.integration.secman.PermissionUtil;
import org.jboss.as.testsuite.integration.secman.servlets.CallPermissionUtilServlet;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
/**
* Abstract parent for tests which creates deployments with library JAR including {@link PermissionUtil}.
*
* @author Josef Cacek
*/
public abstract class AbstractPPTestsWithLibrary extends AbstractPropertyPermissionTests {
private static Logger LOGGER = Logger.getLogger(AbstractPPTestsWithLibrary.class);
/**
* Check access to 'java.home' property.
*/
@Override
protected void checkJavaHomeProperty(URL webAppURL, int expectedStatus) throws Exception {
checkProperty(webAppURL, "java.home", expectedStatus);
}
/**
* Checks access to a system property on the server using {@link CallPermissionUtilServlet}.
*
* @param webAppURL
* @param propertyName
* @param expectedCode expected HTTP Status code
* @throws Exception
*/
protected void checkProperty(final URL webAppURL, final String propertyName, final int expectedCode) throws Exception {
checkProperty(webAppURL, propertyName, expectedCode, null);
}
/**
* Checks access to a system property on the server.
*
* @param webAppURL
* @param propertyName
* @param expectedCode expected HTTP Status code
* @param expectedBody expected response value; if null then response body is not checked
* @throws Exception
*/
@Override
protected void checkProperty(final URL webAppURL, final String propertyName, final int expectedCode,
final String expectedBody) throws Exception {
final URI sysPropUri = new URI(webAppURL.toExternalForm() + CallPermissionUtilServlet.SERVLET_PATH.substring(1) + "?"
+ Utils.encodeQueryParam(CallPermissionUtilServlet.PARAM_PROPERTY_NAME, propertyName));
LOGGER.debug("Checking if '" + propertyName + "' property is available: " + sysPropUri);
final String respBody = Utils.makeCall(sysPropUri, expectedCode);
if (expectedBody != null && HttpServletResponse.SC_OK == expectedCode) {
assertEquals("System property value doesn't match the expected one.", expectedBody, respBody);
}
}
/**
* Create java archive with PropertyReadStaticMethodClass class
*
* @return created java archive
*/
protected static JavaArchive createLibrary() {
final JavaArchive lib = ShrinkWrap.create(JavaArchive.class, "library.jar");
lib.addClasses(PermissionUtil.class);
return lib;
}
}
| 4,004
| 38.653465
| 125
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/propertypermission/SystemPropertiesSetup.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.testsuite.integration.secman.propertypermission;
import org.jboss.as.test.integration.security.common.AbstractSystemPropertiesServerSetupTask;
/**
* Server setup task, which adds a custom system property to AS configuration.
*
* @author Josef Cacek
*/
public class SystemPropertiesSetup extends AbstractSystemPropertiesServerSetupTask {
public static final String PROPERTY_NAME = "custom-test-property";
@Override
protected SystemProperty[] getSystemProperties() {
return new SystemProperty[] { new DefaultSystemProperty(PROPERTY_NAME, PROPERTY_NAME) };
}
}
| 1,633
| 40.897436
| 96
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/propertypermission/AbstractPropertyPermissionTests.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.testsuite.integration.secman.propertypermission;
import static org.jboss.as.testsuite.integration.secman.propertypermission.SystemPropertiesSetup.PROPERTY_NAME;
import static org.junit.Assert.assertEquals;
import java.net.URI;
import java.net.URL;
import java.security.AllPermission;
import java.util.PropertyPermission;
import jakarta.servlet.http.HttpServletResponse;
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.Utils;
import org.jboss.as.test.shared.integration.ejb.security.PermissionUtils;
import org.jboss.as.testsuite.integration.secman.servlets.JSMCheckServlet;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.container.ClassContainer;
import org.jboss.shrinkwrap.api.container.ManifestContainer;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Abstract parent for testcases aimed on PropertyPermission.
*
* @author Josef Cacek
*/
@RunWith(Arquillian.class)
@ServerSetup(SystemPropertiesSetup.class)
@RunAsClient
public abstract class AbstractPropertyPermissionTests {
public static final Asset ALL_PERMISSIONS_XML = PermissionUtils.createPermissionsXmlAsset(new AllPermission());
public static final Asset EMPTY_PERMISSIONS_XML = PermissionUtils.createPermissionsXmlAsset();
public static final Asset GRANT_PERMISSIONS_XML = PermissionUtils.createPermissionsXmlAsset(new PropertyPermission("*",
"read,write"));
public static final Asset LIMITED_PERMISSIONS_XML = PermissionUtils.createPermissionsXmlAsset(new PropertyPermission(
"java.home", "read"));
protected static final String APP_GRANT = "read-props-grant";
protected static final String APP_LIMITED = "read-props-limited";
protected static final String APP_DENY = "read-props-deny";
private static Logger LOGGER = Logger.getLogger(AbstractPropertyPermissionTests.class);
/**
* Checks if the AS runs with security manager enabled.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_GRANT)
public void testJSMEnabled(@ArquillianResource URL webAppURL) throws Exception {
final URI checkJSMuri = new URI(webAppURL.toExternalForm() + JSMCheckServlet.SERVLET_PATH.substring(1));
LOGGER.debug("Checking if JSM is enabled: " + checkJSMuri);
assertEquals("JSM should be enabled.", Boolean.toString(true), Utils.makeCall(checkJSMuri, 200));
}
/**
* Check standard java property access in application, where PropertyPermission for all properties is granted.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_GRANT)
public void testJavaHomePropertyGrant(@ArquillianResource URL webAppURL) throws Exception {
checkJavaHomeProperty(webAppURL, HttpServletResponse.SC_OK);
}
/**
* Check standard java property access in application, where not all PropertyPermissions are granted.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_LIMITED)
public void testJavaHomePropertyLimited(@ArquillianResource URL webAppURL) throws Exception {
checkJavaHomeProperty(webAppURL, HttpServletResponse.SC_OK);
}
/**
* Check standard java property access in application, where no PropertyPermission is granted.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_DENY)
public void testJavaHomePropertyDeny(@ArquillianResource URL webAppURL) throws Exception {
checkJavaHomeProperty(webAppURL, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
* Check AS defined (standalone.xml) property access in application, where PropertyPermission for all properties is granted.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_GRANT)
public void testASLevelPropertyGrant(@ArquillianResource URL webAppURL) throws Exception {
checkTestProperty(webAppURL, HttpServletResponse.SC_OK);
}
/**
* Check AS defined (standalone.xml) property access in application, where not all PropertyPermissions are granted.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_LIMITED)
public void testASLevelPropertyLimited(@ArquillianResource URL webAppURL) throws Exception {
checkTestProperty(webAppURL, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
* Check AS defined (standalone.xml) property access in application, where no PropertyPermission is granted.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_DENY)
public void testASLevelPropertyDeny(@ArquillianResource URL webAppURL) throws Exception {
checkTestProperty(webAppURL, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
* Check access to 'java.home' property.
*/
protected void checkJavaHomeProperty(URL webAppURL, int expectedStatus) throws Exception {
checkProperty(webAppURL, "java.home", expectedStatus, null);
}
/**
* Check access to {@value #APP_BASE_NAME} property.
*/
protected void checkTestProperty(URL webAppURL, final int expectedStatus) throws Exception {
checkProperty(webAppURL, PROPERTY_NAME, expectedStatus, PROPERTY_NAME);
}
/**
* Adds {@link JSMCheckServlet} to the given archive.
*
* @param archive
*/
protected static void addJSMCheckServlet(final ClassContainer<?> archive) {
archive.addClass(JSMCheckServlet.class);
}
/**
* Adds {@link JSMCheckServlet} to the given archive.
*
* @param archive
*/
protected static void addPermissionsXml(final ManifestContainer<?> archive, final Asset permissionsAsset,
final Asset jbossPermissionsAsset) {
if (permissionsAsset != null) {
archive.addAsManifestResource(permissionsAsset, "permissions.xml");
}
if (jbossPermissionsAsset != null) {
archive.addAsManifestResource(jbossPermissionsAsset, "jboss-permissions.xml");
}
}
/**
* Checks access to a system property on the server.
*
* @param webAppURL
* @param propertyName
* @param expectedCode expected HTTP Status code
* @param expectedBody expected response value; if null then response body is not checked
* @throws Exception
*/
protected abstract void checkProperty(final URL webAppURL, final String propertyName, final int expectedCode,
final String expectedBody) throws Exception;
}
| 7,991
| 36.876777
| 128
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/propertypermission/AbstractPPTestsWithJSP.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.testsuite.integration.secman.propertypermission;
import static org.jboss.as.testsuite.integration.secman.propertypermission.SystemPropertiesSetup.PROPERTY_NAME;
import java.net.URL;
import jakarta.servlet.http.HttpServletResponse;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.junit.Test;
/**
* Abstract parent for PropertyPermission testcases, which have also readproperty.jsp page included.
*
* @author Josef Cacek
*/
public abstract class AbstractPPTestsWithJSP extends AbstractPropertyPermissionTests {
/**
* Check standard java property access in application, where PropertyPermission for all properties is granted.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_GRANT)
public void testJavaHomePropertyInJSPGrant(@ArquillianResource URL webAppURL) throws Exception {
checkJavaHomePropertyInJSP(webAppURL, HttpServletResponse.SC_OK);
}
/**
* Check standard java property access in application, where JSP don't get PropertyPermissions (servlets get them).
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_LIMITED)
public void testJavaHomePropertyInJSPLimited(@ArquillianResource URL webAppURL) throws Exception {
checkJavaHomePropertyInJSP(webAppURL, HttpServletResponse.SC_OK);
}
/**
* Check standard java property access in application.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_DENY)
public void testJavaHomePropertyInJSPDeny(@ArquillianResource URL webAppURL) throws Exception {
checkJavaHomePropertyInJSP(webAppURL, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
* Check AS defined (standalone.xml) property access in application, where PropertyPermission for all properties is granted.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_GRANT)
public void testASLevelPropertyInJSPGrant(@ArquillianResource URL webAppURL) throws Exception {
checkTestPropertyInJSP(webAppURL, HttpServletResponse.SC_OK);
}
/**
* Check AS defined (standalone.xml) property access in application, where not all PropertyPermissions are granted.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_LIMITED)
public void testASLevelPropertyInJSPLimited(@ArquillianResource URL webAppURL) throws Exception {
checkTestPropertyInJSP(webAppURL, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
* Check AS defined (standalone.xml) property access in application, where no PropertyPermission is granted.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(APP_DENY)
public void testASLevelPropertyInJSPDeny(@ArquillianResource URL webAppURL) throws Exception {
checkTestPropertyInJSP(webAppURL, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
* Check access to 'java.home' property.
*/
protected void checkJavaHomePropertyInJSP(URL webAppURL, int expectedStatus) throws Exception {
checkPropertyInJSP(webAppURL, "java.home", expectedStatus, "java.home=");
}
/**
* Check access to {@value #WEBAPP_BASE_NAME} property.
*/
protected void checkTestPropertyInJSP(URL webAppURL, final int expectedStatus) throws Exception {
checkPropertyInJSP(webAppURL, PROPERTY_NAME, expectedStatus, PROPERTY_NAME);
}
/**
* Checks access to a system property on the server using <code>readproperty.jsp</code>.
*
* @param webAppURL
* @param propertyName
* @param expectedCode expected HTTP Status code
* @param expectedBodyStart expected beginning of response value; if null then response body is not checked
* @throws Exception
*/
protected abstract void checkPropertyInJSP(final URL webAppURL, final String propertyName, final int expectedCode,
final String expectedBodyStart) throws Exception;
}
| 5,214
| 36.25
| 128
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/propertypermission/EarWithLibPPTestCase.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.testsuite.integration.secman.propertypermission;
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.testsuite.integration.secman.servlets.CallPermissionUtilServlet;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
/**
* Test case, which checks PropertyPermissions assigned to lib of deployed ear applications. The applications try to do a
* protected action and it should either complete successfully if {@link java.util.PropertyPermission} is granted, or fail.
*
* @author Ondrej Lukas
* @author Josef Cacek
*/
@RunWith(Arquillian.class)
@ServerSetup(SystemPropertiesSetup.class)
@RunAsClient
public class EarWithLibPPTestCase extends AbstractPPTestsWithLibrary {
/**
* Creates archive with a tested application.
*
* @return {@link EnterpriseArchive} instance
*/
@Deployment(name = APP_GRANT, testable = false)
public static EnterpriseArchive createDeployment1() {
return earDeployment(APP_GRANT, GRANT_PERMISSIONS_XML);
}
/**
* Creates archive with a tested application.
*
* @return {@link EnterpriseArchive} instance
*/
@Deployment(name = APP_LIMITED, testable = false)
public static EnterpriseArchive createDeployment2() {
return earDeployment(APP_LIMITED, LIMITED_PERMISSIONS_XML);
}
/**
* Creates archive with a tested application.
*
* @return {@link EnterpriseArchive} instance
*/
@Deployment(name = APP_DENY, testable = false)
public static EnterpriseArchive createDeployment3() {
return earDeployment(APP_DENY, EMPTY_PERMISSIONS_XML);
}
private static EnterpriseArchive earDeployment(final String appName, final Asset permissionsXml) {
final WebArchive war = ShrinkWrap.create(WebArchive.class, appName + ".war");
addJSMCheckServlet(war);
war.addClasses(CallPermissionUtilServlet.class);
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, appName + ".ear");
ear.addAsModule(war);
// use just jboss-permissions.xml (and no permissions.xml)
addPermissionsXml(ear, null, permissionsXml);
ear.addAsLibraries(createLibrary());
return ear;
}
}
| 3,602
| 37.329787
| 123
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/propertypermission/WarWithLibPPTestCase.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.testsuite.integration.secman.propertypermission;
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.testsuite.integration.secman.servlets.CallPermissionUtilServlet;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
/**
* Test case, which checks PropertyPermissions assigned to lib of deployed war applications. The applications try to do a
* protected action and it should either complete successfully if {@link java.util.PropertyPermission} is granted, or fail.
*
* @author Ondrej Lukas
* @author Josef Cacek
*/
@RunWith(Arquillian.class)
@ServerSetup(SystemPropertiesSetup.class)
@RunAsClient
public class WarWithLibPPTestCase extends AbstractPPTestsWithLibrary {
/**
* Creates archive with a tested application.
*
* @return {@link WebArchive} instance
*/
@Deployment(name = APP_GRANT, testable = false)
public static WebArchive createDeployment1() {
return warDeployment(APP_GRANT, GRANT_PERMISSIONS_XML);
}
/**
* Creates archive with a tested application.
*
* @return {@link WebArchive} instance
*/
@Deployment(name = APP_LIMITED, testable = false)
public static WebArchive createDeployment2() {
return warDeployment(APP_LIMITED, LIMITED_PERMISSIONS_XML);
}
/**
* Creates archive with a tested application.
*
* @return {@link WebArchive} instance
*/
@Deployment(name = APP_DENY, testable = false)
public static WebArchive createDeployment3() {
return warDeployment(APP_DENY, EMPTY_PERMISSIONS_XML);
}
private static WebArchive warDeployment(final String suffix, final Asset permissionsXml) {
final WebArchive war = ShrinkWrap.create(WebArchive.class, suffix + ".war");
war.addClasses(CallPermissionUtilServlet.class);
addJSMCheckServlet(war);
addPermissionsXml(war, EMPTY_PERMISSIONS_XML, permissionsXml);
war.addAsLibraries(createLibrary());
return war;
}
}
| 3,311
| 37.511628
| 123
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/custompermissions/AbstractGrantCustomPermissionTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, 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.testsuite.integration.secman.custompermissions;
import org.junit.Test;
public abstract class AbstractGrantCustomPermissionTestCase {
protected void checkCustomPermission(String customPermName) {
if (customPermName != null) {
try {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new CustomPermission(customPermName));
} else {
throw new IllegalStateException("Java Security Manager is not initialized");
}
} catch (Exception e) {
e.printStackTrace();
throw new AssertionError(e);
}
}
}
/**
* Test which checks a custom permission.
*/
@Test
public void testMinimumPermission() throws Exception {
String customPermName = "org.jboss.test";
checkCustomPermission(customPermName);
}
/**
* Test which checks we don't have custom permission.
*/
@Test(expected = AssertionError.class)
public void testNoCustomPermissionPermissionsXML() throws Exception {
String customPermName = "org.jboss.test-wrong";
checkCustomPermission(customPermName);
}
}
| 2,314
| 35.171875
| 96
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/custompermissions/Utils.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, 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.testsuite.integration.secman.custompermissions;
import java.io.File;
import java.io.IOException;
import org.jboss.as.test.module.util.TestModule;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
public class Utils {
public static TestModule createTestModule(String jarName, String moduleName, String moduleXmlPath, Class<?>... classes) throws IOException {
File moduleXml = new File(moduleXmlPath);
TestModule module = new TestModule(moduleName, moduleXml);
module.addResource(jarName).addClasses(classes);
module.create();
return module;
}
public static Asset getJBossDeploymentStructure(String... dependencies) {
final StringBuilder sb = new StringBuilder();
sb.append("<jboss-deployment-structure>\n<deployment>\n<dependencies>");
if (dependencies != null) {
for (String moduleName : dependencies) {
sb.append("\n\t<module name='").append(moduleName).append("'/>");
}
}
sb.append("\n</dependencies>\n</deployment>\n</jboss-deployment-structure>");
return new StringAsset(sb.toString());
}
}
| 2,234
| 41.169811
| 144
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/custompermissions/CustomPermission.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, 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.testsuite.integration.secman.custompermissions;
import java.security.BasicPermission;
/**
*
* @author Hynek Švábek <hsvabek@redhat.com>
*
*/
public class CustomPermission extends BasicPermission {
private static final long serialVersionUID = 1L;
public CustomPermission(String name) {
super(name);
}
}
| 1,373
| 35.157895
| 70
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/custompermissions/GrantCustomPermissionModuleTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, 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.testsuite.integration.secman.custompermissions;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
/**
* Test case which checks if permissions.xml which contains CustomPermission
* permission works right. https://issues.jboss.org/browse/JBEAP-903
*
* @author Hynek Švábek <hsvabek@redhat.com>
*
*/
@RunWith(Arquillian.class)
@ServerSetup(GrantCustomPermissionModuleTestCase.CustomPermissionModuleServerSetupTask.class)
public class GrantCustomPermissionModuleTestCase extends AbstractGrantCustomPermissionTestCase {
private static final String DEP_PERMISSIONS_XML_NAME = "DEP_PERMISSIONS_XML.war";
/**
* Creates test web archive.
*
* @return test application
*/
@Deployment
public static WebArchive deployment() {
return ShrinkWrap
.create(WebArchive.class, DEP_PERMISSIONS_XML_NAME)
.addClasses(AbstractGrantCustomPermissionTestCase.class, AbstractCustomPermissionServerSetup.class)
.addAsManifestResource(GrantCustomPermissionModuleTestCase.class.getResource("permissions.xml"), "permissions.xml")
.addAsManifestResource(Utils.getJBossDeploymentStructure("org.jboss.test"), "jboss-deployment-structure.xml");
}
static class CustomPermissionModuleServerSetupTask extends AbstractCustomPermissionServerSetup {
}
}
| 2,618
| 41.241935
| 131
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/custompermissions/AbstractCustomPermissionServerSetup.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, 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.testsuite.integration.secman.custompermissions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.integration.management.ManagementOperations;
import org.jboss.as.test.module.util.TestModule;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.dmr.ModelNode;
public abstract class AbstractCustomPermissionServerSetup implements ServerSetupTask {
private TestModule module;
private List<ModelNode> backupList = new ArrayList<>();
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
this.module = Utils.createTestModule("moduleperm.jar", "org.jboss.test", GrantCustomPermissionModuleMinimumPermissionTestCase.class
.getResource("module.xml").getFile(), CustomPermission.class);
if (writeMinimumPermissions()) {
backupMinimumPermissions(managementClient);
final ModelNode address = new ModelNode();
address.add("subsystem", "security-manager");
address.add("deployment-permissions", "default");
address.protect();
final ModelNode operation = new ModelNode();
operation.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION);
operation.get(ModelDescriptionConstants.OP_ADDR).set(address);
operation.get("name").set("minimum-permissions");
ModelNode customPermission = new ModelNode();
customPermission.get("class").set(new ModelNode(CustomPermission.class.getName()));
customPermission.get("name").set(new ModelNode("org.jboss.test"));
customPermission.get("module").set(new ModelNode("org.jboss.test"));
operation.get("value").set(Arrays.asList(customPermission));
ManagementOperations.executeOperation(managementClient.getControllerClient(), operation);
ServerReload.executeReloadAndWaitForCompletion(managementClient);
}
}
public void backupMinimumPermissions(ManagementClient managementClient) throws Exception {
final ModelNode address = new ModelNode();
address.add("subsystem", "security-manager");
address.add("deployment-permissions", "default");
address.protect();
final ModelNode operation = new ModelNode();
operation.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION);
operation.get(ModelDescriptionConstants.OP_ADDR).set(address);
operation.get("name").set("minimum-permissions");
ModelNode result = ManagementOperations.executeOperation(managementClient.getControllerClient(), operation);
if(result.isDefined()){
List<ModelNode> list = result.asList();
for (ModelNode modelNode : list) {
ModelNode customPermission = new ModelNode();
customPermission.get("class").set(modelNode.get("class"));
customPermission.get("name").set(modelNode.get("name"));
customPermission.get("module").set(modelNode.get("module"));
backupList.add(customPermission);
}
}
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
this.module.remove();
//restore minimum permissions
if (writeMinimumPermissions()) {
final ModelNode address = new ModelNode();
address.add("subsystem", "security-manager");
address.add("deployment-permissions", "default");
address.protect();
final ModelNode operation = new ModelNode();
operation.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION);
operation.get(ModelDescriptionConstants.OP_ADDR).set(address);
operation.get("name").set("minimum-permissions");
operation.get("value").set(backupList);
ManagementOperations.executeOperation(managementClient.getControllerClient(), operation);
ServerReload.executeReloadAndWaitForCompletion(managementClient);
}
}
protected boolean writeMinimumPermissions() {
return false;
};
}
| 5,523
| 44.652893
| 139
|
java
|
null |
wildfly-main/testsuite/integration/secman/src/test/java/org/jboss/as/testsuite/integration/secman/custompermissions/GrantCustomPermissionModuleMinimumPermissionTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, 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.testsuite.integration.secman.custompermissions;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
/**
* Test case which checks if subsystem with minimumPermissions setting which
* contains CustomPermission permission works right.
* https://issues.jboss.org/browse/JBEAP-903
*
* @author Hynek Švábek <hsvabek@redhat.com>
*
*/
@RunWith(Arquillian.class)
@ServerSetup(GrantCustomPermissionModuleMinimumPermissionTestCase.GrantCustomPermissionModuleMinimumPermissionServerSetupTask.class)
public class GrantCustomPermissionModuleMinimumPermissionTestCase extends AbstractGrantCustomPermissionTestCase {
private static final String DEP_WITHOUT_PERMISSIONS_XML_NAME = "DEP_WITHOUT_PERMISSIONS_XML.war";
/**
* Creates test web archive.
*
* @return test application
*/
@Deployment
public static WebArchive deployment() {
return ShrinkWrap.create(WebArchive.class, DEP_WITHOUT_PERMISSIONS_XML_NAME)
.addClasses(AbstractGrantCustomPermissionTestCase.class, AbstractCustomPermissionServerSetup.class)
.addAsManifestResource(Utils.getJBossDeploymentStructure("org.jboss.test"), "jboss-deployment-structure.xml");
}
static class GrantCustomPermissionModuleMinimumPermissionServerSetupTask extends AbstractCustomPermissionServerSetup {
@Override
protected boolean writeMinimumPermissions() {
return true;
}
}
}
| 2,708
| 40.045455
| 132
|
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/web/ssl/HTTPSWebConnectorTestCase.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.manualmode.web.ssl;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.COMPOSITE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PORT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING_GROUP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS;
import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode;
import static org.jboss.as.test.integration.security.common.SSLTruststoreUtil.HTTPS_PORT_VERIFY_FALSE;
import static org.jboss.as.test.integration.security.common.SSLTruststoreUtil.HTTPS_PORT_VERIFY_TRUE;
import static org.jboss.as.test.integration.security.common.SSLTruststoreUtil.HTTPS_PORT_VERIFY_WANT;
import static org.jboss.as.test.integration.security.common.Utils.makeCallWithHttpClient;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.File;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLPeerUnverifiedException;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.http.client.HttpClient;
import org.jboss.arquillian.container.test.api.ContainerController;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.categories.CommonCriteria;
import org.jboss.as.test.integration.security.common.AbstractSecurityDomainsServerSetupTask;
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.SecurityTraceLoggingServerSetupTask;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.integration.security.common.config.JSSE;
import org.jboss.as.test.integration.security.common.config.SecureStore;
import org.jboss.as.test.integration.security.common.config.SecurityDomain;
import org.jboss.as.test.integration.security.common.config.SecurityModule;
import org.jboss.as.test.integration.security.common.servlets.PrincipalPrintingServlet;
import org.jboss.as.test.integration.security.common.servlets.SimpleSecuredServlet;
import org.jboss.as.test.integration.security.common.servlets.SimpleServlet;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
/**
* Testing https connection to Web Connector with configured two-way SSL.
* HTTP client has set client keystore with valid/invalid certificate, which is used for
* authentication to management interface. Result of authentication depends on whether client
* certificate is accepted in server truststore. HTTP client uses client truststore with accepted
* server certificate to authenticate server identity.
*
* Keystores and truststores have valid certificates until 25 October 2033.
*
* @author Filip Bogyai
* @author Josef cacek
*/
@RunWith(Arquillian.class)
@RunAsClient
@Category(CommonCriteria.class)
@Ignore("[WFLY-15177] Complete porting of HTTPSWebConnectorTestCase to Elytron.")
public class HTTPSWebConnectorTestCase {
private static final String STANDARD_SOCKETS = "standard-sockets";
private static final String HTTPS = "https";
public static final int HTTPS_PORT = 8444;
private static Logger LOGGER = Logger.getLogger(HTTPSWebConnectorTestCase.class);
private static SecurityTraceLoggingServerSetupTask TRACE_SECURITY = new SecurityTraceLoggingServerSetupTask();
private static final File WORK_DIR = new File("https-workdir");
public static final File SERVER_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.SERVER_KEYSTORE);
public static final File SERVER_TRUSTSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.SERVER_TRUSTSTORE);
public static final File CLIENT_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.CLIENT_KEYSTORE);
public static final File CLIENT_TRUSTSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.CLIENT_TRUSTSTORE);
public static final File UNTRUSTED_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.UNTRUSTED_KEYSTORE);
private static final String HTTPS_NAME_VERIFY_NOT_REQUESTED = "https-verify-not-requested";
private static final String HTTPS_NAME_VERIFY_REQUESTED = "https-verify-requested";
private static final String HTTPS_NAME_VERIFY_REQUIRED = "https-verify-required";
private static final String SSL_CONTEXT_DEFAULT = "TestSSLContextDefault";
private static final String SSL_CONTEXT_NEED = "TestSSLContextNeed";
private static final String SSL_CONTEXT_WANT = "TestSSLContextWant";
private static final String APP_CONTEXT = HTTPS;
private static final String SECURED_SERVLET_WITH_SESSION = SimpleSecuredServlet.SERVLET_PATH + "?"
+ SimpleSecuredServlet.CREATE_SESSION_PARAM + "=true";
private static final String SECURITY_DOMAIN_CERT = "client cert domain";
private static final String SECURITY_DOMAIN_JSSE = "jsse_!@#$%^&*()_domain";
public static final String CONTAINER = "default-jbossas";
@ArquillianResource
private static ContainerController containerController;
@ArquillianResource
private Deployer deployer;
@BeforeClass
public static void noJDK14Plus() {
Assume.assumeFalse("Avoiding JDK 14 due to https://issues.jboss.org/browse/WFCORE-4532", "14".equals(System.getProperty("java.specification.version")));
}
@Deployment(name = APP_CONTEXT, testable = false, managed = false)
public static WebArchive deployment() {
LOGGER.trace("Start deployment " + APP_CONTEXT);
final WebArchive war = ShrinkWrap.create(WebArchive.class, APP_CONTEXT + ".war");
// AddRoleLoginModule.class
war.addClasses(SimpleServlet.class, SimpleSecuredServlet.class,
PrincipalPrintingServlet.class);
war.addAsWebInfResource(HTTPSWebConnectorTestCase.class.getPackage(), "web.xml", "web.xml");
war.addAsWebInfResource(HTTPSWebConnectorTestCase.class.getPackage(), "jboss-web.xml", "jboss-web.xml");
return war;
}
@Test
@InSequence(-1)
public void startAndSetupContainer() throws Exception {
LOGGER.trace("*** starting server");
containerController.start(CONTAINER);
ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient();
ManagementClient managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(),
TestSuiteEnvironment.getServerPort(), "remote+http");
LOGGER.trace("*** will configure server now");
serverSetup(managementClient);
deployer.deploy(APP_CONTEXT);
}
/**
* @test.tsfi tsfi.keystore.file
* @test.tsfi tsfi.truststore.file
* @test.objective Testing default HTTPs connector with verify-client attribute set to "false". The CLIENT-CERT
* authentication (BaseCertLoginModule) is configured for this test. Trusted client is allowed to access
* both secured/unsecured resource. Untrusted client can only access unprotected resources.
* @test.expectedResult Trusted client has access to protected and unprotected resources. Untrusted client has only access
* to unprotected resources.
* @throws Exception
*/
@Test
@InSequence(1)
public void testNonVerifyingConnector() throws Exception {
Assume.assumeFalse(SystemUtils.IS_JAVA_1_6 && SystemUtils.JAVA_VENDOR.toUpperCase(Locale.ENGLISH).contains("IBM"));
final URL printPrincipalUrl = getServletUrl(HTTPS_PORT_VERIFY_FALSE, PrincipalPrintingServlet.SERVLET_PATH);
final URL securedUrl = getServletUrl(HTTPS_PORT_VERIFY_FALSE, SECURED_SERVLET_WITH_SESSION);
final URL unsecuredUrl = getServletUrl(HTTPS_PORT_VERIFY_FALSE, SimpleServlet.SERVLET_PATH);
final HttpClient httpClient = getHttpClient(CLIENT_KEYSTORE_FILE);
final HttpClient httpClientUntrusted = getHttpClient(UNTRUSTED_KEYSTORE_FILE);
try {
makeCallWithHttpClient(printPrincipalUrl, httpClient, HttpServletResponse.SC_FORBIDDEN);
String responseBody = makeCallWithHttpClient(securedUrl, httpClient, HttpServletResponse.SC_OK);
assertEquals("Secured page was not reached", SimpleSecuredServlet.RESPONSE_BODY, responseBody);
String principal = makeCallWithHttpClient(printPrincipalUrl, httpClient, HttpServletResponse.SC_OK);
assertEquals("Unexpected principal", "cn=client", principal.toLowerCase());
responseBody = makeCallWithHttpClient(unsecuredUrl, httpClientUntrusted, HttpServletResponse.SC_OK);
assertEquals("Secured page was not reached", SimpleServlet.RESPONSE_BODY, responseBody);
try {
makeCallWithHttpClient(securedUrl, httpClientUntrusted, HttpServletResponse.SC_FORBIDDEN);
} catch (SSLHandshakeException e) {
// OK
} catch (java.net.SocketException se) {
// OK - on windows usually fails with this one
}
} finally {
httpClient.getConnectionManager().shutdown();
httpClientUntrusted.getConnectionManager().shutdown();
}
}
/**
* @test.tsfi tsfi.keystore.file
* @test.tsfi tsfi.truststore.file
* @test.objective Testing default HTTPs connector with verify-client attribute set to "want". The CLIENT-CERT
* authentication (BaseCertLoginModule) is configured for this test. Trusted client is allowed to access
* both secured/unsecured resource. Untrusted client can only access unprotected resources.
* @test.expectedResult Trusted client has access to protected and unprotected resources. Untrusted client has only access
* to unprotected resources.
* @throws Exception
*/
@Test
@InSequence(1)
public void testWantVerifyConnector() throws Exception {
Assume.assumeFalse(SystemUtils.IS_JAVA_1_6 && SystemUtils.JAVA_VENDOR.toUpperCase(Locale.ENGLISH).contains("IBM"));
final URL printPrincipalUrl = getServletUrl(HTTPS_PORT_VERIFY_WANT, PrincipalPrintingServlet.SERVLET_PATH);
final URL securedUrl = getServletUrl(HTTPS_PORT_VERIFY_WANT, SECURED_SERVLET_WITH_SESSION);
final URL unsecuredUrl = getServletUrl(HTTPS_PORT_VERIFY_WANT, SimpleServlet.SERVLET_PATH);
final HttpClient httpClient = getHttpClient(CLIENT_KEYSTORE_FILE);
final HttpClient httpClientUntrusted = getHttpClient(UNTRUSTED_KEYSTORE_FILE);
try {
makeCallWithHttpClient(printPrincipalUrl, httpClientUntrusted, HttpServletResponse.SC_FORBIDDEN);
final String principal = makeCallWithHttpClient(printPrincipalUrl, httpClient, HttpServletResponse.SC_OK);
assertEquals("Unexpected principal", "cn=client", principal.toLowerCase());
String responseBody = makeCallWithHttpClient(unsecuredUrl, httpClient, HttpServletResponse.SC_OK);
assertEquals("Unsecured page was not reached", SimpleSecuredServlet.RESPONSE_BODY, responseBody);
responseBody = makeCallWithHttpClient(securedUrl, httpClient, HttpServletResponse.SC_OK);
assertEquals("Secured page was not reached", SimpleSecuredServlet.RESPONSE_BODY, responseBody);
responseBody = makeCallWithHttpClient(unsecuredUrl, httpClientUntrusted, HttpServletResponse.SC_OK);
assertEquals("Unsecured page was not reached", SimpleServlet.RESPONSE_BODY, responseBody);
makeCallWithHttpClient(securedUrl, httpClientUntrusted, HttpServletResponse.SC_FORBIDDEN);
} finally {
httpClient.getConnectionManager().shutdown();
httpClientUntrusted.getConnectionManager().shutdown();
}
}
/**
* @test.tsfi tsfi.keystore.file
* @test.tsfi tsfi.truststore.file
* @test.objective Testing default HTTPs connector with verify-client attribute set to "true". The CLIENT-CERT
* authentication (BaseCertLoginModule) is configured for this test. Trusted client is allowed to access
* both secured/unsecured resource. Untrusted client is not allowed to access anything.
* @test.expectedResult Trusted client has access to protected and unprotected resources. Untrusted client can't access
* anything.
* @throws Exception
*/
@Test
@InSequence(1)
public void testVerifyingConnector() throws Exception {
final HttpClient httpClient = getHttpClient(CLIENT_KEYSTORE_FILE);
final HttpClient httpClientUntrusted = getHttpClient(UNTRUSTED_KEYSTORE_FILE);
try {
final URL printPrincipalUrl = getServletUrl(HTTPS_PORT_VERIFY_TRUE, PrincipalPrintingServlet.SERVLET_PATH);
final URL securedUrl = getServletUrl(HTTPS_PORT_VERIFY_TRUE, SECURED_SERVLET_WITH_SESSION);
final URL unsecuredUrl = getServletUrl(HTTPS_PORT_VERIFY_TRUE, SimpleServlet.SERVLET_PATH);
String principal = makeCallWithHttpClient(printPrincipalUrl, httpClient, HttpServletResponse.SC_OK);
assertEquals("Unexpected principal", "cn=client", principal.toLowerCase());
String responseBody = makeCallWithHttpClient(securedUrl, httpClient, HttpServletResponse.SC_OK);
assertEquals("Secured page was not reached", SimpleSecuredServlet.RESPONSE_BODY, responseBody);
try {
makeCallWithHttpClient(unsecuredUrl, httpClientUntrusted, HttpServletResponse.SC_FORBIDDEN);
fail("Untrusted client should not be authenticated.");
} catch (SSLHandshakeException |SSLPeerUnverifiedException | SocketException e) {
//depending on the OS and the version of HTTP client in use any one of these exceptions may be thrown
//in particular the SocketException gets thrown on Windows
// OK
} catch (SSLException e) {
if (! (e.getCause() instanceof SocketException)) { // OK
throw e;
}
}
try {
makeCallWithHttpClient(printPrincipalUrl, httpClientUntrusted, HttpServletResponse.SC_FORBIDDEN);
fail("Untrusted client should not be authenticated.");
} catch (SSLHandshakeException |SSLPeerUnverifiedException | SocketException e) {
// OK
} catch (SSLException e) {
if (! (e.getCause() instanceof SocketException)) { // OK
throw e;
}
}
try {
makeCallWithHttpClient(securedUrl, httpClientUntrusted, HttpServletResponse.SC_FORBIDDEN);
fail("Untrusted client should not be authenticated.");
} catch (SSLHandshakeException |SSLPeerUnverifiedException | SocketException e) {
// OK
} catch (SSLException e) {
if (! (e.getCause() instanceof SocketException)) { // OK
throw e;
}
}
} finally {
httpClient.getConnectionManager().shutdown();
httpClientUntrusted.getConnectionManager().shutdown();
}
}
@Test
@InSequence(3)
public void stopContainer() throws Exception {
deployer.undeploy(APP_CONTEXT);
final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient();
final ManagementClient managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(),
TestSuiteEnvironment.getServerPort(), "remote+http");
LOGGER.trace("*** reseting test configuration");
serverTearDown(managementClient);
LOGGER.trace("*** stopping container");
containerController.stop(CONTAINER);
}
private URL getServletUrl(int connectorPort, String servletPath) throws MalformedURLException {
return new URL(HTTPS, TestSuiteEnvironment.getServerAddress(), connectorPort, "/" + APP_CONTEXT + servletPath);
}
private static HttpClient getHttpClient(File keystoreFile) {
return SSLTruststoreUtil.getHttpClientWithSSL(keystoreFile, SecurityTestConstants.KEYSTORE_PASSWORD,
CLIENT_TRUSTSTORE_FILE, SecurityTestConstants.KEYSTORE_PASSWORD);
}
private void serverSetup(ManagementClient managementClient) throws Exception {
FileUtils.deleteDirectory(WORK_DIR);
WORK_DIR.mkdirs();
Utils.createKeyMaterial(WORK_DIR);
// Uncomment if TRACE logging is necessary. Don't leave it on all the time; CI resources aren't free.
//TRACE_SECURITY.setup(managementClient, null);
SecurityDomainsSetup.INSTANCE.setup(managementClient, null);
final ModelControllerClient client = managementClient.getControllerClient();
// add new SSLContext
ModelNode addSSLContexts = createAddSSLContexts();
Utils.applyUpdate(addSSLContexts, client);
LOGGER.trace("*** restarting server");
containerController.stop(CONTAINER);
containerController.start(CONTAINER);
addHttpsConnector(SSL_CONTEXT_DEFAULT, HTTPS_NAME_VERIFY_NOT_REQUESTED, HTTPS_PORT_VERIFY_FALSE, client);
addHttpsConnector(SSL_CONTEXT_WANT, HTTPS_NAME_VERIFY_REQUESTED, HTTPS_PORT_VERIFY_WANT, client);
addHttpsConnector(SSL_CONTEXT_NEED, HTTPS_NAME_VERIFY_REQUIRED, HTTPS_PORT_VERIFY_TRUE, client);
}
private ModelNode createAddSSLContexts() throws Exception {
List<ModelNode> operations = new ArrayList<>();
// Shared by all contexts
addKeyManager(operations);
addTrustManager(operations);
addSSLContext(operations, SSL_CONTEXT_DEFAULT, false, false);
addSSLContext(operations, SSL_CONTEXT_NEED, false, true);
addSSLContext(operations, SSL_CONTEXT_WANT, true, false);
return Util.createCompositeOperation(operations);
}
private ModelNode createRemoveSSLContexts() throws Exception {
List<ModelNode> operations = new ArrayList<>();
operations.add(createOpNode("subsystem=elytron/server-ssl-context=" + SSL_CONTEXT_DEFAULT, ModelDescriptionConstants.REMOVE));
operations.add(createOpNode("subsystem=elytron/server-ssl-context=" + SSL_CONTEXT_NEED, ModelDescriptionConstants.REMOVE));
operations.add(createOpNode("subsystem=elytron/server-ssl-context=" + SSL_CONTEXT_WANT, ModelDescriptionConstants.REMOVE));
operations.add(createOpNode("subsystem=elytron/trust-manager=TestTrustManager", ModelDescriptionConstants.REMOVE));
operations.add(createOpNode("subsystem=elytron/key-manager=TestKeyManager", ModelDescriptionConstants.REMOVE));
operations.add(createOpNode("subsystem=elytron/key-store=TestStore", ModelDescriptionConstants.REMOVE));
return Util.createCompositeOperation(operations);
}
private void addSSLContext(List<ModelNode> operations, final String name, final boolean wantClientAuth,
final boolean needClientAuth) throws Exception {
final ModelNode addOp = createOpNode("subsystem=elytron/server-ssl-context=" + name, ADD);
addOp.get("key-manager").set("TestKeyManager");
addOp.get("trust-manager").set("TestTrustManager");
final ModelNode protocols = new ModelNode();
protocols.add("TLSv1");
addOp.get("protocols").set(protocols);
if (wantClientAuth) {
addOp.get("want-client-auth").set(true);
}
if (needClientAuth) {
addOp.get("need-client-auth").set(true);
}
operations.add(addOp);
}
private void addTrustManager(List<ModelNode> operations) throws Exception {
final ModelNode addOp = createOpNode("subsystem=elytron/trust-manager=TestTrustManager", ADD);
addOp.get("key-store").set("TestStore");
operations.add(addOp);
}
private void addKeyManager(List<ModelNode> operations) throws Exception {
addKeyStore(operations);
final ModelNode addOp = createOpNode("subsystem=elytron/key-manager=TestKeyManager", ADD);
ModelNode credentialReference = new ModelNode();
credentialReference.get("clear-text").set(SecurityTestConstants.KEYSTORE_PASSWORD);
addOp.get("credential-reference").set(credentialReference);
addOp.get("key-store").set("TestStore");
operations.add(addOp);
}
private void addKeyStore(List<ModelNode> operations) throws Exception {
final ModelNode addOp = createOpNode("subsystem=elytron/key-store=TestStore", ADD);
addOp.get("path").set(SERVER_KEYSTORE_FILE.getAbsolutePath());
ModelNode credentialReference = new ModelNode();
credentialReference.get("clear-text").set(SecurityTestConstants.KEYSTORE_PASSWORD);
addOp.get("credential-reference").set(credentialReference);
operations.add(addOp);
}
private void addHttpsConnector(String sslContextName, String httpsName, int httpsPort, ModelControllerClient client)
throws Exception {
final ModelNode compositeOp = Util.createOperation(COMPOSITE, PathAddress.EMPTY_ADDRESS);
final ModelNode steps = compositeOp.get(STEPS);
// /socket-binding-group=standard-sockets/socket-binding=NAME:add(port=PORT)
ModelNode op = Util.createAddOperation(PathAddress.pathAddress(SOCKET_BINDING_GROUP, STANDARD_SOCKETS).append(
SOCKET_BINDING, httpsName));
op.get(PORT).set(httpsPort);
steps.add(op);
ModelNode operation = createOpNode("subsystem=undertow/server=default-server/https-listener=" + httpsName,
ModelDescriptionConstants.ADD);
operation.get("socket-binding").set(httpsName);
operation.get("ssl-context").set(sslContextName);
steps.add(operation);
Utils.applyUpdate(compositeOp, client);
}
private void serverTearDown(ManagementClient managementClient) throws Exception {
// delete test security domains
SecurityDomainsSetup.INSTANCE.tearDown(managementClient, null);
final ModelControllerClient client = managementClient.getControllerClient();
// delete https web connectors
rmHttpsConnector(HTTPS_NAME_VERIFY_NOT_REQUESTED, client);
rmHttpsConnector(HTTPS_NAME_VERIFY_REQUESTED, client);
rmHttpsConnector(HTTPS_NAME_VERIFY_REQUIRED, client);
ModelNode operation = createRemoveSSLContexts();
Utils.applyUpdate(operation, client);
FileUtils.deleteDirectory(WORK_DIR);
// Uncomment if TRACE logging is necessary. Don't leave it on all the time; CI resources aren't free.
//TRACE_SECURITY.tearDown(managementClient, null);
}
private void rmHttpsConnector(String httpsName, ModelControllerClient client) throws Exception {
final ModelNode compositeOp = Util.createOperation(COMPOSITE, PathAddress.EMPTY_ADDRESS);
final ModelNode steps = compositeOp.get(STEPS);
ModelNode operation = createOpNode("subsystem=undertow/server=default-server/https-listener=" + httpsName,
ModelDescriptionConstants.REMOVE);
steps.add(operation);
steps.add(Util.createRemoveOperation(PathAddress.pathAddress(SOCKET_BINDING_GROUP, STANDARD_SOCKETS).append(
SOCKET_BINDING, httpsName)));
Utils.applyUpdate(compositeOp, client);
}
/**
* Security domains configuration for this test.
*/
private static class SecurityDomainsSetup extends AbstractSecurityDomainsServerSetupTask {
private static final SecurityDomainsSetup INSTANCE = new SecurityDomainsSetup();
@Override
protected SecurityDomain[] getSecurityDomains() throws Exception {
final SecurityDomain sd = new SecurityDomain.Builder()
.name(SECURITY_DOMAIN_CERT)
.loginModules(
new SecurityModule.Builder().name("org.jboss.security.auth.spi.BaseCertLoginModule")
.putOption("securityDomain", SECURITY_DOMAIN_JSSE)
.putOption("password-stacking", "useFirstPass").build(),
new SecurityModule.Builder().name("REMOVED").flag("optional") // AddRoleLoginModule.class.getName()
.putOption("password-stacking", "useFirstPass")
.putOption("roleName", SimpleSecuredServlet.ALLOWED_ROLE).build()) //
.build();
final SecurityDomain sdJsse = new SecurityDomain.Builder()
.name(SECURITY_DOMAIN_JSSE)
.jsse(new JSSE.Builder().trustStore(
new SecureStore.Builder().type("JKS").url(SERVER_TRUSTSTORE_FILE.toURI().toURL())
.password(SecurityTestConstants.KEYSTORE_PASSWORD).build()) //
.build()) //
.build();
return new SecurityDomain[] { sdJsse, sd };
}
}
}
| 27,567
| 49.032668
| 160
|
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/web/ssl/AbstractCertificateLoginModuleTestCase.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.manualmode.web.ssl;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALLOW_RESOURCE_SERVICE_RESTART;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PORT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROTOCOL;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLLBACK_ON_RUNTIME_FAILURE;
import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode;
import static org.jboss.as.test.integration.security.common.Utils.makeCallWithHttpClient;
import static org.junit.Assert.assertEquals;
import static org.jboss.as.test.shared.ServerReload.executeReloadAndWaitForCompletion;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Locale;
import javax.net.ssl.SSLHandshakeException;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
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.SecurityTraceLoggingServerSetupTask;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.integration.security.common.servlets.PrincipalPrintingServlet;
import org.jboss.as.test.integration.security.common.servlets.SimpleSecuredServlet;
import org.jboss.as.test.integration.security.common.servlets.SimpleServlet;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.junit.Assume;
/**
* Abstract class which serve as a base for CertificateLoginModule tests. It is
* used for setting up server/client keystores, https connector and contains
* useful methods for testing two-way SSL connection.
*
* @author Filip Bogyai
*/
public abstract class AbstractCertificateLoginModuleTestCase {
private static Logger LOGGER = Logger.getLogger(AbstractCertificateLoginModuleTestCase.class);
protected static SecurityTraceLoggingServerSetupTask TRACE_SECURITY = new SecurityTraceLoggingServerSetupTask();
protected static final File WORK_DIR = new File("target" + File.separatorChar + "test-classes" + File.separatorChar + "keystores-workdir");
protected static final File SERVER_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.SERVER_KEYSTORE);
protected static final File SERVER_TRUSTSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.SERVER_TRUSTSTORE);
protected static final File CLIENT_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.CLIENT_KEYSTORE);
protected static final File CLIENT_TRUSTSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.CLIENT_TRUSTSTORE);
protected static final File UNTRUSTED_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.UNTRUSTED_KEYSTORE);
protected static final String HTTPS_REALM = "https_realm";
protected static final String CONTAINER = "default-jbossas";
protected static final String SECURED_SERVLET_WITH_SESSION = SimpleSecuredServlet.SERVLET_PATH + "?"
+ SimpleSecuredServlet.CREATE_SESSION_PARAM + "=true";
private static final int HTTPS_PORT = 8444;
/**
* Testing access to HTTPS connector which have configured truststore with
* trusted certificates. Client with trusted certificate is allowed to
* access both secured/unsecured resource. Client with untrusted certificate
* can only access unprotected resources.
*
* @throws Exception
*/
public void testLoginWithCertificate(String appName) throws Exception {
Assume.assumeFalse(SystemUtils.IS_JAVA_1_6 && SystemUtils.JAVA_VENDOR.toUpperCase(Locale.ENGLISH).contains("IBM"));
final URL printPrincipalUrl = getServletUrl(HTTPS_PORT, appName, PrincipalPrintingServlet.SERVLET_PATH);
final URL securedUrl = getServletUrl(HTTPS_PORT, appName, SECURED_SERVLET_WITH_SESSION);
final URL unsecuredUrl = getServletUrl(HTTPS_PORT, appName, SimpleServlet.SERVLET_PATH);
final HttpClient httpClient = getHttpsClient(CLIENT_KEYSTORE_FILE);
final HttpClient httpClientUntrusted = getHttpsClient(UNTRUSTED_KEYSTORE_FILE);
try {
makeCallWithHttpClient(printPrincipalUrl, httpClient, HttpServletResponse.SC_FORBIDDEN);
String responseBody = makeCallWithHttpClient(securedUrl, httpClient, HttpServletResponse.SC_OK);
assertEquals("Secured page was not reached", SimpleSecuredServlet.RESPONSE_BODY, responseBody);
String principal = makeCallWithHttpClient(printPrincipalUrl, httpClient, HttpServletResponse.SC_OK);
assertEquals("Unexpected principal", "cn=client", principal.toLowerCase());
responseBody = makeCallWithHttpClient(unsecuredUrl, httpClientUntrusted, HttpServletResponse.SC_OK);
assertEquals("Secured page was not reached", SimpleServlet.RESPONSE_BODY, responseBody);
try {
makeCallWithHttpClient(securedUrl, httpClientUntrusted, HttpServletResponse.SC_FORBIDDEN);
} catch (SSLHandshakeException e) {
// OK
} catch (java.net.SocketException se) {
// OK - on windows usually fails with this one
}
} finally {
httpClient.getConnectionManager().shutdown();
httpClientUntrusted.getConnectionManager().shutdown();
}
}
public URL getServletUrl(int connectorPort, String appName, String servletPath) throws MalformedURLException {
return new URL("https", TestSuiteEnvironment.getServerAddress(), connectorPort, "/" + appName + servletPath);
}
/**
* Requests given URL and checks if the returned HTTP status code is the
* expected one. Returns HTTP response body
*/
public static String makeCall(URL url, HttpClient httpClient, int expectedStatusCode) throws ClientProtocolException, IOException,
URISyntaxException {
String httpResponseBody = null;
HttpGet httpGet = new HttpGet(url.toURI());
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
LOGGER.trace("Request to: " + url + " responds: " + statusCode);
assertEquals("Unexpected status code", expectedStatusCode, statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
httpResponseBody = EntityUtils.toString(response.getEntity());
EntityUtils.consume(entity);
}
return httpResponseBody;
}
public static HttpClient getHttpsClient(File keystoreFile) {
return SSLTruststoreUtil.getHttpClientWithSSL(keystoreFile, SecurityTestConstants.KEYSTORE_PASSWORD, CLIENT_TRUSTSTORE_FILE,
SecurityTestConstants.KEYSTORE_PASSWORD);
}
static class HTTPSConnectorSetup implements ServerSetupTask {
protected static final HTTPSConnectorSetup INSTANCE = new HTTPSConnectorSetup();
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
deleteWorkDir();
WORK_DIR.mkdirs();
Utils.createKeyMaterial(WORK_DIR);
// Uncomment if TRACE logging is necessary. Don't leave it on all the time; CI resources aren't free.
//TRACE_SECURITY.setup(managementClient, null);
final ModelControllerClient client = managementClient.getControllerClient();
// add new HTTPS_REALM with SSL
ModelNode operation = createOpNode("core-service=management/security-realm=" + HTTPS_REALM, ModelDescriptionConstants.ADD);
Utils.applyUpdate(operation, client);
operation = createOpNode("core-service=management/security-realm=" + HTTPS_REALM + "/authentication=truststore",
ModelDescriptionConstants.ADD);
operation.get("keystore-path").set(SERVER_TRUSTSTORE_FILE.getAbsolutePath());
operation.get("keystore-password").set(SecurityTestConstants.KEYSTORE_PASSWORD);
Utils.applyUpdate(operation, client);
operation = createOpNode("core-service=management/security-realm=" + HTTPS_REALM + "/server-identity=ssl",
ModelDescriptionConstants.ADD);
operation.get(PROTOCOL).set("TLSv1");
operation.get("keystore-path").set(SERVER_KEYSTORE_FILE.getAbsolutePath());
operation.get("keystore-password").set(SecurityTestConstants.KEYSTORE_PASSWORD);
Utils.applyUpdate(operation, client);
executeReloadAndWaitForCompletion(managementClient, 100000);
operation = createOpNode("socket-binding-group=standard-sockets/socket-binding=https2" , ADD);
operation.get(PORT).set(Integer.toString(HTTPS_PORT));
operation.get(OPERATION_HEADERS, ROLLBACK_ON_RUNTIME_FAILURE).set(false);
operation.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true);
Utils.applyUpdate(operation, client);
operation = createOpNode("subsystem=undertow/server=default-server/https-listener=https2", ModelDescriptionConstants.ADD);
operation.get("socket-binding").set("https2");
operation.get("security-realm").set(HTTPS_REALM);
Utils.applyUpdate(operation, client);
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
ModelNode operation = createOpNode("subsystem=undertow/server=default-server/https-listener=https2",
ModelDescriptionConstants.REMOVE);
operation.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(false);
Utils.applyUpdate(operation, managementClient.getControllerClient());
operation = createOpNode("socket-binding-group=standard-sockets/socket-binding=https2",
ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, managementClient.getControllerClient());
operation = createOpNode("core-service=management/security-realm=" + HTTPS_REALM, ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, managementClient.getControllerClient());
deleteWorkDir();
return;
// Uncomment if TRACE logging is necessary. Don't leave it on all the time; CI resources aren't free.
//TRACE_SECURITY.tearDown(managementClient, null);
}
}
protected static void deleteWorkDir() throws IOException {
FileUtils.deleteDirectory(WORK_DIR);
}
}
| 12,570
| 50.101626
| 143
|
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/Util.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.ejb;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Properties;
/**
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
* @author <a href="mailto:istudens@redhat.com">Ivo Studensky</a>
*/
public class Util {
/**
* Creates JNDI context string based on given parameters.
* See details at https://docs.jboss.org/author/display/AS71/EJB+invocations+from+a+remote+client+using+JNDI
*
* @param appName - typically the ear name without the .ear
* - could be empty string when deploying just jar with EJBs
* @param moduleName - jar file name without trailing .jar
* @param distinctName - AS7 allows each deployment to have an (optional) distinct name
* - could be empty string when not specified
* @param beanName - The EJB name which by default is the simple class name of the bean implementation class
* @param viewClassName - the remote view is fully qualified class name of @Remote EJB interface
* @param isStateful - if the bean is stateful set to true
* @return - JNDI context string to use in your client JNDI lookup
*/
public static String createRemoteEjbJndiContext(
String appName,
String moduleName,
String distinctName,
String beanName,
String viewClassName,
boolean isStateful) {
return "ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName
+ (isStateful ? "?stateful" : "");
}
/**
* Helper to create InitialContext with necessary properties.
*
* @return new InitialContext.
* @throws javax.naming.NamingException
*/
public static Context createNamingContext() throws NamingException {
final Properties jndiProps = new Properties();
jndiProps.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
return new InitialContext(jndiProps);
}
/**
* Helper to create the InitialContext with the given properties.
*
* @param properties the environment properties
* @return the constructed InitialContext
* @throws NamingException if an error occurs while creating the InitialContext
*/
public static Context createNamingContext(final Properties properties) throws NamingException {
final Properties jndiProps = new Properties();
jndiProps.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
jndiProps.putAll(properties);
return new InitialContext(jndiProps);
}
public static <T> T lookup(final String name, final Class<T> cls) throws NamingException {
InitialContext ctx = new InitialContext();
try {
return cls.cast(ctx.lookup(name));
} finally {
ctx.close();
}
}
}
| 4,046
| 39.069307
| 117
|
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/interceptor/serverside/SubstituteSampleBeanRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.manualmode.ejb.interceptor.serverside;
import jakarta.ejb.Remote;
@Remote
public interface SubstituteSampleBeanRemote {
String getSimpleName();
}
| 1,201
| 39.066667
| 70
|
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/interceptor/serverside/InterceptorSubstituteTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.manualmode.ejb.interceptor.serverside;
import static org.jboss.as.controller.client.helpers.ClientConstants.NAME;
import static org.jboss.as.controller.client.helpers.ClientConstants.OP;
import static org.jboss.as.controller.client.helpers.ClientConstants.OP_ADDR;
import static org.jboss.as.controller.client.helpers.ClientConstants.SUBSYSTEM;
import static org.jboss.as.controller.client.helpers.ClientConstants.UNDEFINE_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.client.helpers.ClientConstants.VALUE;
import static org.jboss.as.controller.client.helpers.ClientConstants.WRITE_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MODULE;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.jboss.arquillian.container.test.api.ContainerController;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.container.test.api.TargetsContainer;
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.client.helpers.Operations;
import org.jboss.as.test.shared.integration.ejb.interceptor.serverside.AbstractServerInterceptorsSetupTask;
import org.jboss.as.test.shared.integration.ejb.interceptor.serverside.InterceptorModule;
import org.jboss.as.test.module.util.TestModule;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* A test case substitutes existing interceptor module with a newer one and checks its availability.
* See https://issues.jboss.org/browse/WFLY-6143 for more details.
*
* @author <a href="mailto:szhantem@redhat.com">Sultan Zhantemirov</a> (c) 2019 Red Hat, inc.
*/
@RunWith(Arquillian.class)
@ServerSetup(InterceptorSubstituteTestCase.SetupTask.class)
@RunAsClient
public class InterceptorSubstituteTestCase {
private static final Logger log = Logger.getLogger(InterceptorSubstituteTestCase.class);
@ArquillianResource
private ContainerController controller;
@ArquillianResource
private Deployer deployer;
@ArquillianResource
private ManagementClient managementClient;
private static Context ctx;
private static final String DEPLOYMENT = "server-interceptor-substitute";
private static final String CONTAINER = "jbossas-non-clustered";
@Deployment(name = DEPLOYMENT, managed = false, testable = false)
@TargetsContainer(CONTAINER)
public static Archive createDeployment() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, DEPLOYMENT + ".jar");
jar.addPackage(InterceptorSubstituteTestCase.class.getPackage());
jar.addPackage(AbstractServerInterceptorsSetupTask.class.getPackage());
return jar;
}
@Before
public void before() throws Exception {
final Properties jndiProperties = new Properties();
jndiProperties.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
jndiProperties.putAll(getEJBClientProperties());
ctx = new InitialContext(jndiProperties);
controller.start(CONTAINER);
log.trace("===Appserver started===");
deployer.deploy(DEPLOYMENT);
log.trace("===Deployment deployed===");
}
@After
public void after() throws Exception {
ctx.close();
try {
if (!controller.isStarted(CONTAINER)) {
controller.start(CONTAINER);
}
deployer.undeploy(DEPLOYMENT);
log.trace("===Deployment undeployed===");
} finally {
controller.stop(CONTAINER);
log.trace("===Appserver stopped===");
}
}
/**
* Create a module with a newer interceptor module and substitute a deployed one. Server restart is needed.
*/
@Test
public void substituteInterceptorModule() throws Exception {
SubstituteSampleBeanRemote bean = (SubstituteSampleBeanRemote) ctx.lookup("ejb:" + "" + "/" + DEPLOYMENT + "/" + "" + "/" +
SubstituteSampleBean.class.getSimpleName() + "!" + SubstituteSampleBeanRemote.class.getName());
Assert.assertNotNull(bean);
Assert.assertEquals(SubstituteInterceptor.PREFIX + SubstituteSampleBean.class.getSimpleName(), bean.getSimpleName());
// on Windows machines module jar is locked by a process,
// so in order to replace the module we need to restart the server
controller.stop(CONTAINER);
log.trace("===appserver stopped===");
InterceptorModule updatedInterceptorModule = createUpdatedInterceptorModule();
controller.start(CONTAINER);
log.trace("===appserver started again===");
modifyServerInterceptorsAttribute(updatedInterceptorModule);
// "server-interceptors" attribute changing requires server restart
controller.stop(CONTAINER);
log.trace("===appserver stopped===");
controller.start(CONTAINER);
log.trace("===appserver started again===");
try {
SubstituteSampleBeanRemote bean2 = (SubstituteSampleBeanRemote) ctx.lookup("ejb:" + "" + "/" + DEPLOYMENT + "/" + "" + "/" +
SubstituteSampleBean.class.getSimpleName() + "!" + SubstituteSampleBeanRemote.class.getName());
Assert.assertNotNull(bean2);
String beanName = bean2.getSimpleName();
Assert.assertEquals(UpdatedInterceptor.PREFIX + SubstituteSampleBean.class.getSimpleName(), beanName);
} finally {
reverServerInterceptorsAttribute();
// "server-interceptors" attribute changing requires server restart
controller.stop(CONTAINER);
log.trace("===appserver stopped===");
// on Windows machines module jar is locked by a process,
// so in order to remove the module we need to have the server stopped
updatedInterceptorModule.getTestModule().remove();
}
}
private InterceptorModule createUpdatedInterceptorModule() {
InterceptorModule updatedInterceptorModule = new InterceptorModule(
UpdatedInterceptor.class,
"interceptor-module",
"updated-module.xml",
InterceptorSubstituteTestCase.class.getResource("updated-module.xml"),
"server-side-interceptor-updated.jar"
);
try {
URL url = updatedInterceptorModule.getModuleXmlPath();
if (url == null) {
throw new IllegalStateException("Could not find " + updatedInterceptorModule.getModuleXmlName());
}
File moduleXmlFile = new File(url.toURI());
updatedInterceptorModule.setTestModule(new TestModule(updatedInterceptorModule.getModuleName(), moduleXmlFile));
JavaArchive jar = updatedInterceptorModule.getTestModule().addResource(updatedInterceptorModule.getJarName());
jar.addClass(updatedInterceptorModule.getInterceptorClass());
updatedInterceptorModule.getTestModule().create(true);
} catch (Exception e) {
throw new RuntimeException("An error while creating interceptor module", e);
}
return updatedInterceptorModule;
}
private void modifyServerInterceptorsAttribute(InterceptorModule updatedInterceptorModule) throws IOException {
final ModelNode op = new ModelNode();
op.get(OP_ADDR).set(SUBSYSTEM, "ejb3");
op.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
op.get(NAME).set("server-interceptors");
final ModelNode value = new ModelNode();
ModelNode node = new ModelNode();
node.get(MODULE).set(updatedInterceptorModule.getModuleName());
node.get("class").set(updatedInterceptorModule.getInterceptorClass().getName());
value.add(node);
op.get(VALUE).set(value);
managementClient.getControllerClient().execute(op);
}
private void reverServerInterceptorsAttribute() throws IOException {
final ModelNode op = new ModelNode();
op.get(OP_ADDR).set(SUBSYSTEM, "ejb3");
op.get(OP).set(UNDEFINE_ATTRIBUTE_OPERATION);
op.get(NAME).set("server-interceptors");
final ModelNode operationResult = managementClient.getControllerClient().execute(op);
// check whether the operation was successful
assertTrue(Operations.isSuccessfulOutcome(operationResult));
}
private static Properties getEJBClientProperties() throws Exception {
final InputStream inputStream = InterceptorSubstituteTestCase.class.getResourceAsStream("jboss-ejb-client.properties");
if (inputStream == null) {
throw new IllegalStateException("Could not find jboss-ejb-client.properties in classpath");
}
final Properties properties = new Properties();
properties.load(inputStream);
return properties;
}
static class SetupTask extends AbstractServerInterceptorsSetupTask.SetupTask {
@Override
public List<InterceptorModule> getModules() {
return Collections.singletonList(new InterceptorModule(
SubstituteInterceptor.class,
"interceptor-module",
"module.xml",
InterceptorSubstituteTestCase.class.getResource("module.xml"),
"server-side-interceptor-substitute.jar"
)
);
}
}
}
| 11,193
| 42.55642
| 136
|
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/interceptor/serverside/UpdatedInterceptor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.manualmode.ejb.interceptor.serverside;
import jakarta.interceptor.AroundInvoke;
import jakarta.interceptor.InvocationContext;
public class UpdatedInterceptor {
static final String PREFIX = "UpdatedInterceptor:";
@AroundInvoke
public Object aroundInvoke(final InvocationContext invocationContext) throws Exception {
return PREFIX + invocationContext.proceed();
}
}
| 1,441
| 39.055556
| 92
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.