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/shared/src/main/java/org/jboss/as/test/integration/transactions/RemoteLookups.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 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.test.integration.transactions; import java.net.URI; import java.net.URISyntaxException; import java.util.Properties; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.rmi.PortableRemoteObject; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.shared.integration.ejb.security.CallbackHandler; import org.jboss.logging.Logger; /** * Util class which is used for remote lookups in transaction related tests. * * @author Ondra Chaloupka <ochaloup@redhat.com> */ public final class RemoteLookups { private static final Logger log = Logger.getLogger(RemoteLookups.class); private RemoteLookups() { // not instance here } public static <T> T lookupModule(InitialContext ctx, Class<T> beanType) throws NamingException { String lookupString = String.format("java:module/%s!%s", beanType.getSimpleName(), beanType.getName()); log.debugf("looking for: %s", lookupString); return beanType.cast(ctx.lookup(lookupString)); } public static <T> T lookupEjbStateless(InitialContext ctx, String archiveName, Class<? extends T> beanType, Class<T> remoteInterface) throws NamingException { return lookupEjb(ctx, archiveName, beanType, remoteInterface, false); } public static <T> T lookupEjbStateful(InitialContext ctx, String archiveName, Class<? extends T> beanType, Class<T> remoteInterface) throws NamingException { return lookupEjb(ctx, archiveName, beanType, remoteInterface, true); } public static <T> T lookupEjbStateless(String host, int port, String archiveName, Class<? extends T> beanType, Class<T> remoteInterface) throws NamingException, URISyntaxException { return lookupEjb(host, port, archiveName, beanType, remoteInterface, false); } public static <T> T lookupEjbStateful(String host, int port, String archiveName, Class<? extends T> beanType, Class<T> remoteInterface) throws NamingException, URISyntaxException { return lookupEjb(host, port, archiveName, beanType, remoteInterface, true); } public static <T> T lookupEjbStateless(final ManagementClient managementClient, final String archiveName, Class<? extends T> beanType, final Class<T> remoteInterface) throws NamingException, URISyntaxException { return lookupEjb(managementClient, archiveName, beanType, remoteInterface, false); } public static <T> T lookupIIOP(String serverHost, int iiopPort, Class<T> homeClass, Class<?> beanClass) throws NamingException { final Properties prope = new Properties(); prope.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.cosnaming.CNCtxFactory"); prope.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.iiop.naming:org.jboss.naming.client"); prope.put(Context.PROVIDER_URL, "corbaloc::" + serverHost +":" + iiopPort + "/JBoss/Naming/root"); final InitialContext context = new InitialContext(prope); final Object ejbHome = context.lookup(beanClass.getSimpleName()); return homeClass.cast(PortableRemoteObject.narrow(ejbHome, homeClass)); } private static <T> T lookupEjb(InitialContext ctx, String archiveName, Class<? extends T> beanType, Class<T> remoteInterface, boolean isStateful) throws NamingException { String ejbLookup = org.jboss.as.test.shared.integration.ejb.security.Util.createRemoteEjbJndiContext( "", archiveName, "", beanType.getSimpleName(), remoteInterface.getName(), isStateful); log.debugf("looking for: %s", ejbLookup); return remoteInterface.cast(ctx.lookup(ejbLookup)); } private static <T> T lookupEjb(String host, int port, String archiveName, Class<? extends T> beanType, Class<T> remoteInterface, boolean isStateful) throws NamingException, URISyntaxException { InitialContext ctx = getRemoteContext(host, port); return lookupEjb(ctx, archiveName, beanType, remoteInterface, isStateful); } private static <T> T lookupEjb(ManagementClient managementClient, String archiveName, Class<? extends T> beanType, Class<T> remoteInterface, boolean isStateful) throws NamingException, URISyntaxException { InitialContext ctx = getRemoteContext(managementClient); return lookupEjb(ctx, archiveName, beanType, remoteInterface, isStateful); } private static InitialContext getRemoteContext(final String host, int port) throws NamingException, URISyntaxException { Properties props = getEjbClientProperties(); URI namingUri = new URI("remote+http", null, host, port, "", "", ""); props.put(Context.PROVIDER_URL, namingUri.toString()); return new InitialContext(props); } private static InitialContext getRemoteContext(final ManagementClient managementClient) throws NamingException, URISyntaxException { Properties props = getEjbClientProperties(); URI webUri = managementClient.getWebUri(); URI namingUri = new URI("remote+http", webUri.getUserInfo(), webUri.getHost(), webUri.getPort(), "", "", ""); props.put(Context.PROVIDER_URL, namingUri.toString()); return new InitialContext(props); } private static Properties getEjbClientProperties() { final Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, org.wildfly.naming.client.WildFlyInitialContextFactory.class.getName()); props.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false"); props.put("jboss.naming.client.security.callback.handler.class", CallbackHandler.class.getName()); props.put("jboss.naming.client.ejb.context", true); return props; } }
7,021
49.517986
138
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/transactions/RecoveryExecutor.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 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.transactions; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import java.io.IOException; import java.util.concurrent.atomic.AtomicReference; import com.arjuna.ats.arjuna.recovery.RecoveryDriver; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.ClientConstants; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.management.ManagementOperations; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; /** * A helper class which wraps remote execution of the transaction recovery. */ public class RecoveryExecutor { private static final Logger log = Logger.getLogger(RecoveryExecutor.class); private static final ModelNode ADDRESS_TRANSACTIONS = new ModelNode().add("subsystem", "transactions"); private static final ModelNode ADDRESS_SOCKET_BINDING = new ModelNode().add(ClientConstants.SOCKET_BINDING_GROUP, "standard-sockets"); private static final ModelNode ADDRESS_TRANSACTIONS_LOG_STORE = ADDRESS_TRANSACTIONS .clone().add("log-store", "log-store"); static { ADDRESS_TRANSACTIONS.protect(); ADDRESS_TRANSACTIONS.protect(); ADDRESS_SOCKET_BINDING.protect(); } private static final int DEFAULT_SOCKET_READ_SCAN_TIMEOUT_MS = 60 * 1000; private static final int RECOVERY_SCAN_RETRY_COUNT = 5; private final ManagementClient managementClient; private final AtomicReference<RecoveryDriver> recoveryDriverReference = new AtomicReference<>(); public RecoveryExecutor(ManagementClient managementClient) { this.managementClient = managementClient; } /** * Run transaction recovery with default read socket timeout. * See more at {@link #runTransactionRecovery(int)}. * * @return true if recovery was successfully run without any issue, false otherwise */ public boolean runTransactionRecovery() { return runTransactionRecovery(DEFAULT_SOCKET_READ_SCAN_TIMEOUT_MS); } /** * <p> * Run the transaction recovery. It expects the <code>transaction-listener</code> is enabled * (<code>&sol;subsystem=transactions&sol;:write-attribute(name=transaction-listener, value=true)</code>). * </p> * <p> * Returning from this method could not necessary means that whole recovery cycle was fully finished. * To be sure that the whole recovery cycle is finished is recommended to run this method twice (one by one). * After the second call it's ensured that one(!) recovery cycle is fully finished. * </p> * <p> * The method returns true if the recovery socket listener call succeeded and when the recovery cycle was run * without any issue. An issue means there is an error on recovery processing of an XAResource - * e.g. one example of such failure could be a database is down and recovery was not able to connect. * </p> * * @param socketReadTimeout socket timeout for launching the recovery against the transaction listener socket, * expected to be opened already * @return true if recovery was successfully run without any issue, false otherwise */ public boolean runTransactionRecovery(int socketReadTimeout) { try { return getRecoveryDriver().synchronousVerboseScan(TimeoutUtil.adjust(socketReadTimeout), RECOVERY_SCAN_RETRY_COUNT); } catch (Exception e) { throw new IllegalStateException("Error when triggering transaction recovery synchronous scan with RecoveryDriver " + recoveryDriverReference.get() + ", based on the management client " + managementClient, e); } } /** * Running WildFly CLI operations to run ':recover' operations on all in-doubt transactions. */ public void cliRecoverAllTransactions() { executeOperation(managementClient, ADDRESS_TRANSACTIONS_LOG_STORE, "probe"); ModelNode logStoreModelNode = null; try { logStoreModelNode = readResource(managementClient, ADDRESS_TRANSACTIONS_LOG_STORE); } catch (MgmtOperationException | IOException e) { throw new IllegalStateException("Cannot read content of the transaction log store at " + ADDRESS_TRANSACTIONS_LOG_STORE + " with the management client" + managementClient, e); } for (ModelNode txns: logStoreModelNode.get("transactions").asList()) { String txnName = txns.asProperty().getName(); for(ModelNode participants: txns.get(txnName).get("participants").asList()) { String participantName = participants.asProperty().getName(); ModelNode participantAddress = ADDRESS_TRANSACTIONS_LOG_STORE.clone() .add("transactions", txnName) .add("participants", participantName); executeOperation(managementClient, participantAddress, "recover"); } } } private RecoveryDriver getRecoveryDriver() { if(recoveryDriverReference.get() != null) return recoveryDriverReference.get(); String host = ""; int port = 0; try { String transactionSocketBinding = readAttribute(managementClient, ADDRESS_TRANSACTIONS, "socket-binding").asString(); final ModelNode addressSocketBinding = ADDRESS_SOCKET_BINDING.clone(); addressSocketBinding.add(ClientConstants.SOCKET_BINDING, transactionSocketBinding); host = readAttribute(managementClient, addressSocketBinding, "bound-address").asString(); port = readAttribute(managementClient, addressSocketBinding, "bound-port").asInt(); recoveryDriverReference.compareAndSet(null, new RecoveryDriver(port, host)); return recoveryDriverReference.get(); } catch (MgmtOperationException | IOException e) { throw new IllegalStateException("Cannot obtain RecoveryDriver for host:port (" + host + ":" + port +") " + "to contact the transaction recovery listener", e); } } private ModelNode readAttribute(final ManagementClient managementClient, ModelNode address, String name) throws IOException, MgmtOperationException { final ModelNode operation = new ModelNode(); operation.get(OP_ADDR).set(address); operation.get(OP).set(ClientConstants.READ_ATTRIBUTE_OPERATION); operation.get(ModelDescriptionConstants.INCLUDE_DEFAULTS).set("true"); operation.get(ModelDescriptionConstants.RESOLVE_EXPRESSIONS).set("true"); operation.get(ClientConstants.NAME).set(name); return ManagementOperations.executeOperation(managementClient.getControllerClient(), operation); } private ModelNode readResource(final ManagementClient managementClient, ModelNode address) throws IOException, MgmtOperationException { final ModelNode operation = new ModelNode(); operation.get(OP_ADDR).set(address); operation.get(OP).set(ClientConstants.READ_RESOURCE_OPERATION); operation.get(ModelDescriptionConstants.INCLUDE_DEFAULTS).set("true"); operation.get(ModelDescriptionConstants.RESOLVE_EXPRESSIONS).set("true"); operation.get(ModelDescriptionConstants.RECURSIVE).set("true"); operation.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set("true"); return ManagementOperations.executeOperation(managementClient.getControllerClient(), operation); } private void executeOperation(final ManagementClient managementClient, ModelNode address, String operationName) { final ModelNode operation = new ModelNode(); operation.get(OP_ADDR).set(address); operation.get(OP).set(operationName); try { // on the execution "outcome" different from the "success" the mgmt exception is thrown ManagementOperations.executeOperation(managementClient.getControllerClient(), operation); } catch (MgmtOperationException | IOException e) { throw new IllegalStateException("Cannot probe transaction subsystem log store at" + ADDRESS_TRANSACTIONS_LOG_STORE + " via the management client " + managementClient, e); } } }
9,611
50.956757
153
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/transactions/TransactionCheckerSingleton.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 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.test.integration.transactions; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import jakarta.ejb.LocalBean; import jakarta.ejb.Singleton; /** * Singleton class used as log for actions done during testing. * * @author Ondra Chaloupka <ochaloup@redhat.com> */ @Singleton @LocalBean public class TransactionCheckerSingleton implements TransactionCheckerSingletonRemote { private final AtomicInteger committed = new AtomicInteger(); private final AtomicInteger prepared = new AtomicInteger(); private final AtomicInteger rolledback = new AtomicInteger(); private final AtomicInteger synchronizedBegin = new AtomicInteger(); private final AtomicInteger synchronizedBefore = new AtomicInteger(); private final AtomicInteger synchronizedAfter = new AtomicInteger(); private final AtomicInteger synchronizedAfterCommitted = new AtomicInteger(); private final AtomicInteger synchronizedAfterRolledBack = new AtomicInteger(); private final Map<String,String> messages = new ConcurrentHashMap<>(); @Override public int getCommitted() { return committed.get(); } @Override public void addCommit() { committed.incrementAndGet(); } @Override public int getPrepared() { return prepared.get(); } @Override public void addPrepare() { prepared.incrementAndGet(); } @Override public int getRolledback() { return rolledback.get(); } @Override public void addRollback() { rolledback.incrementAndGet(); } @Override public boolean isSynchronizedBefore() { return synchronizedBefore.get() > 0; } @Override public void setSynchronizedBefore() { synchronizedBefore.incrementAndGet(); } @Override public boolean isSynchronizedAfter() { return synchronizedAfter.get() > 0; } @Override public void setSynchronizedAfter(boolean isCommit) { synchronizedAfter.incrementAndGet(); if(isCommit) { synchronizedAfterCommitted.incrementAndGet(); } else { synchronizedAfterRolledBack.incrementAndGet(); } } @Override public boolean isSynchronizedBegin() { return synchronizedBegin.get() > 0; } @Override public void setSynchronizedBegin() { synchronizedBegin.incrementAndGet(); } @Override public void resetCommitted() { committed.set(0); } @Override public void resetPrepared() { prepared.set(0); } @Override public void resetRolledback() { rolledback.set(0); } @Override public void resetSynchronizedBefore() { synchronizedBefore.set(0); } @Override public void resetSynchronizedAfter() { synchronizedAfter.set(0); synchronizedAfterCommitted.set(0); synchronizedAfterRolledBack.set(0); } @Override public void resetSynchronizedBegin() { synchronizedBegin.set(0); } @Override public int countSynchronizedBefore() { return synchronizedBefore.get(); } @Override public int countSynchronizedAfter() { return synchronizedAfter.get(); } @Override public int countSynchronizedAfterCommitted() { return synchronizedAfterCommitted.get(); } @Override public int countSynchronizedAfterRolledBack() { return synchronizedAfterRolledBack.get(); } @Override public int countSynchronizedBegin() { return synchronizedBegin.get(); } @Override public void addMessage(String msg) { messages.put(msg,msg); } @Override public Collection<String> getMessages() { return messages.values(); } @Override public void resetMessages() { messages.clear(); } @Override public void resetAll() { resetCommitted(); resetPrepared(); resetRolledback(); resetSynchronizedAfter(); resetSynchronizedBefore(); resetSynchronizedBegin(); resetMessages(); } }
5,251
25.39196
87
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/transactions/TestSynchronization.java
/* * JBoss, Home of Professional Open Source * Copyright 2016, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.transactions; import jakarta.transaction.Synchronization; import org.jboss.logging.Logger; /** * Transaction {@link Synchronization} class for testing purposes. * * @author Ondra Chaloupka <ochaloup@redhat.com> */ public class TestSynchronization implements Synchronization { private static final Logger log = Logger.getLogger(TestSynchronization.class); private TransactionCheckerSingletonRemote checker; public TestSynchronization(TransactionCheckerSingletonRemote checker) { this.checker = checker; } @Override public void beforeCompletion() { log.tracef("beforeCompletion called"); checker.setSynchronizedBefore(); } /** * For status see {@link jakarta.transaction.Status}. */ @Override public void afterCompletion(int status) { log.tracef("afterCompletion called with status '%s'", status); boolean isCommitted = status == jakarta.transaction.Status.STATUS_COMMITTED ? true : false; checker.setSynchronizedAfter(isCommitted); } }
2,103
34.661017
99
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/transactions/spi/TestLastResource.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 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.test.integration.transactions.spi; import org.jboss.as.test.integration.transactions.TestXAResource; import org.jboss.as.test.integration.transactions.TransactionCheckerSingleton; import org.jboss.tm.LastResource; /** * Test {@link LastResource} class which causes that <code>XAOnePhaseResource</code> * will be instantiated at <code>TransactionImple#createRecord</code>.<br> * The information about {@link LastResource} is taken from definition * <code>jtaEnvironmentBean.setLastResourceOptimisationInterfaceClassName</code> * * @author Ondra Chaloupka <ochaloup@redhat.com> */ public class TestLastResource extends TestXAResource implements LastResource { public TestLastResource(TransactionCheckerSingleton checker) { super(checker); } public TestLastResource(TestAction testAction, TransactionCheckerSingleton checker) { super(testAction, checker); } }
1,950
39.645833
89
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/transactions/spi/TestXAResourceRecoveryHelper.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 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.transactions.spi; import java.util.Vector; import javax.transaction.xa.XAResource; import com.arjuna.ats.arjuna.recovery.RecoveryManager; import com.arjuna.ats.arjuna.recovery.RecoveryModule; import com.arjuna.ats.internal.jta.recovery.arjunacore.XARecoveryModule; import com.arjuna.ats.jta.recovery.XAResourceRecoveryHelper; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.ejb.EJB; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; import org.jboss.as.test.integration.transactions.PersistentTestXAResource; import org.jboss.as.test.integration.transactions.TestXAResource; import org.jboss.as.test.integration.transactions.TransactionCheckerSingleton; import org.jboss.logging.Logger; /** * <p> * Singleton startup class which instantiate the {@link XAResourceRecoveryHelper} * for {@link TestXAResource} and {@link PersistentTestXAResource} created in the <code>testsuite/shared</code> * module for testing transactional behaviour. * </p> * <p> * The recovery helper is registered within the {@link XARecoveryModule}. That's the way which is provided * by Narayana to work with the {@link XAResource}s during recovery. * The {@link XAResourceRecoveryHelper} then provides information on unfinished {@link javax.transaction.xa.Xid} * of the particular {@link XAResource} that the helper is responsible for. * </p> * <p> * If the arquillian test deployment contains this class the recovery handling * is able to use the test xa resources during recovery. * </p> */ @Singleton @Startup public class TestXAResourceRecoveryHelper implements XAResourceRecoveryHelper { private static final Logger log = Logger.getLogger(TestXAResourceRecoveryHelper.class); // instantiated on singleton start-up private TestXAResource testXaResourceInstance; private TestXAResource persistentTestXaResourceInstance; @EJB private TransactionCheckerSingleton transactionCheckerSingleton; /** * Singleton lifecycle method. * Register the recovery module with the transaction manager. */ @PostConstruct public void postConstruct() { log.debug("TestXAResourceRecoveryHelper starting"); this.testXaResourceInstance = new TestXAResource(transactionCheckerSingleton); this.persistentTestXaResourceInstance = new PersistentTestXAResource(transactionCheckerSingleton); getRecoveryModule().addXAResourceRecoveryHelper(this); } /** * Singleton lifecycle method. * Unregister the recovery module from the transaction manager. */ @PreDestroy public void preDestroy() { log.debug("TestXAResourceRecoveryHelper stopping"); getRecoveryModule().removeXAResourceRecoveryHelper(this); } /** * Implementing {@link XAResourceRecoveryHelper#initialise(String)}. * Narayana does not use this. */ public boolean initialise(String param) throws Exception { return true; } /** * Implementing {@link XAResourceRecoveryHelper#getXAResources()} * Returning the test {@link XAResource}s which are then used during recovery by {@link XARecoveryModule} * where the {@link XAResource#recover(int)} is invoked. */ public XAResource[] getXAResources() throws Exception { log.debugf("getXAResources() instances: %s and %s", testXaResourceInstance, persistentTestXaResourceInstance); return new XAResource[]{testXaResourceInstance, persistentTestXaResourceInstance}; } /** * A way how to to get {@link XARecoveryModule} from Narayna where the recovery helper can be registered into. * * @return Narayana instantiated {@link XARecoveryModule} */ private XARecoveryModule getRecoveryModule() { for (RecoveryModule recoveryModule : ((Vector<RecoveryModule>) RecoveryManager.manager().getModules())) { if (recoveryModule instanceof XARecoveryModule) { return (XARecoveryModule) recoveryModule; } } throw new IllegalStateException("Cannot find XARecoveryModule which is necessary " + "for recovery initialization of the test XAResources"); } }
5,257
40.401575
118
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/WebSecurityPasswordBasedBase.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.test.integration.security; import org.junit.Test; /** * Base class for web security tests that are based on passwords * * @author Anil Saldhana */ public abstract class WebSecurityPasswordBasedBase { /** * Test with user "anil" who has the right password and the right role to access the servlet * * @throws Exception */ @Test public void testPasswordBasedSuccessfulAuth() throws Exception { makeCall("anil", "anil", 200); } /** * <p> * Test with user "marcus" who has the right password but does not have the right role * </p> * <p> * Should be a HTTP/403 * </p> * * @throws Exception */ @Test public void testPasswordBasedUnsuccessfulAuth() throws Exception { makeCall("marcus", "marcus", 403); } /** * Method that needs to be overridden with the HTTPClient code * * @param user username * @param pass password * @param expectedCode http status code * @throws Exception */ protected abstract void makeCall(String user, String pass, int expectedCode) throws Exception; }
2,183
30.2
98
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/SecurityTraceLoggingServerSetupTask.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.security.common; import java.util.Arrays; import java.util.Collection; import org.jboss.as.arquillian.container.ManagementClient; /** * ServerSetupTask implementation which enables TRACE log-level for security related packages. * * @author Josef Cacek */ public class SecurityTraceLoggingServerSetupTask extends AbstractTraceLoggingServerSetupTask { @Override protected Collection<String> getCategories(ManagementClient managementClient, String containerId) { return Arrays.asList("org.jboss.security", "org.jboss.as.security", "org.picketbox", "org.apache.catalina.authenticator", "org.jboss.as.web.security", "org.jboss.as.domain.management.security", "org.wildfly.security", "org.wildfly.elytron"); } }
1,828
40.568182
124
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/AbstractTraceLoggingServerSetupTask.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.security.common; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.operations.common.Util; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; /** * * @author Josef Cacek */ public abstract class AbstractTraceLoggingServerSetupTask implements ServerSetupTask { private static final Logger LOGGER = Logger.getLogger(AbstractTraceLoggingServerSetupTask.class); private static final PathAddress PATH_LOGGING = PathAddress.pathAddress(SUBSYSTEM, "logging"); protected Collection<String> categories; /* * (non-Javadoc) * * @see org.jboss.as.arquillian.api.ServerSetupTask#setup(org.jboss.as.arquillian.container.ManagementClient, * java.lang.String) */ @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { categories = getCategories(managementClient, containerId); if (categories == null || categories.isEmpty()) { LOGGER.warn("getCategories() returned empty collection."); return; } final List<ModelNode> updates = new ArrayList<ModelNode>(); for (String category : categories) { if (category == null || category.length() == 0) { LOGGER.warn("Empty category name provided."); continue; } ModelNode op = Util.createAddOperation(PATH_LOGGING.append("logger", category)); op.get("level").set("TRACE"); updates.add(op); } ModelNode op = Util.createEmptyOperation("undefine-attribute", PATH_LOGGING.append("console-handler", "CONSOLE")); op.get("name").set("level"); updates.add(op); CoreUtils.applyUpdates(updates, managementClient.getControllerClient()); } /* * (non-Javadoc) * * @see org.jboss.as.arquillian.api.ServerSetupTask#tearDown(org.jboss.as.arquillian.container.ManagementClient, * java.lang.String) */ @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { if (categories == null || categories.isEmpty()) { return; } final List<ModelNode> updates = new ArrayList<ModelNode>(); for (String category : categories) { if (category == null || category.length() == 0) { continue; } updates.add(Util.createRemoveOperation(PATH_LOGGING.append("logger", category))); } ModelNode op = Util.createEmptyOperation("write-attribute", PATH_LOGGING.append("console-handler", "CONSOLE")); op.get("name").set("level"); op.get("value").set("INFO"); updates.add(op); CoreUtils.applyUpdates(updates, managementClient.getControllerClient()); } protected abstract Collection<String> getCategories(ManagementClient managementClient, String containerId); }
4,270
37.477477
122
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/Utils.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.security.common; import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.security.KeyStore; import java.security.MessageDigest; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Base64; import java.util.List; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.auth.login.Configuration; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import javax.security.auth.x500.X500Principal; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.apache.directory.server.annotations.CreateTransport; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.ProtocolException; import org.apache.http.StatusLine; import org.apache.http.auth.AuthSchemeProvider; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.RedirectStrategy; import org.apache.http.client.config.AuthSchemes; import org.apache.http.client.config.RequestConfig; 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.client.protocol.HttpClientContext; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.impl.auth.BasicSchemeFactory; import org.apache.http.impl.auth.DigestSchemeFactory; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultRedirectStrategy; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.OperationBuilder; import org.jboss.as.network.NetworkUtils; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.wildfly.security.x500.cert.SelfSignedX509CertificateAndSigningKey; /** * Common utilities for JBoss AS security tests. * * @author Jan Lanik * @author Josef Cacek */ public class Utils extends CoreUtils { private static final Logger LOGGER = Logger.getLogger(Utils.class); public static final String UTF_8 = "UTF-8"; private static final char[] KEYSTORE_CREATION_PASSWORD = "123456".toCharArray(); private static void createKeyStoreTrustStore(KeyStore keyStore, KeyStore trustStore, String DN, String alias) throws Exception { X500Principal principal = new X500Principal(DN); SelfSignedX509CertificateAndSigningKey selfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey.builder() .setKeyAlgorithmName("RSA") .setSignatureAlgorithmName("SHA256withRSA") .setDn(principal) .setKeySize(1024) .build(); X509Certificate certificate = selfSignedX509CertificateAndSigningKey.getSelfSignedCertificate(); keyStore.setKeyEntry(alias, selfSignedX509CertificateAndSigningKey.getSigningKey(), KEYSTORE_CREATION_PASSWORD, new X509Certificate[]{certificate}); if(trustStore != null) trustStore.setCertificateEntry(alias, certificate); } private static KeyStore loadKeyStore() throws Exception{ KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); return ks; } private static void createTemporaryCertFile(X509Certificate cert, File outputFile) throws Exception { try (FileOutputStream fos = new FileOutputStream(outputFile)){ fos.write(cert.getTBSCertificate()); } } private static void createTemporaryKeyStoreFile(KeyStore keyStore, File outputFile) throws Exception { try (FileOutputStream fos = new FileOutputStream(outputFile)){ keyStore.store(fos, KEYSTORE_CREATION_PASSWORD); } } private static void generateKeyMaterial(final File keyStoreDir) throws Exception { KeyStore clientKeyStore = loadKeyStore(); KeyStore clientTrustStore = loadKeyStore(); KeyStore serverKeyStore = loadKeyStore(); KeyStore serverTrustStore = loadKeyStore(); KeyStore untrustedKeyStore = loadKeyStore(); createKeyStoreTrustStore(clientKeyStore, serverTrustStore, "CN=client", "cn=client"); createKeyStoreTrustStore(serverKeyStore, clientTrustStore, "CN=server", "cn=server"); createKeyStoreTrustStore(untrustedKeyStore, null, "CN=untrusted", "cn=untrusted"); File clientCertFile = new File(keyStoreDir, "client.crt"); File clientKeyFile = new File(keyStoreDir, "client.keystore"); File clientTrustFile = new File(keyStoreDir, "client.truststore"); File serverCertFile = new File(keyStoreDir, "server.crt"); File serverKeyFile = new File(keyStoreDir, "server.keystore"); File serverTrustFile = new File(keyStoreDir, "server.truststore"); File untrustedCertFile = new File(keyStoreDir, "untrusted.crt"); File untrustedKeyFile = new File(keyStoreDir, "untrusted.keystore"); createTemporaryCertFile((X509Certificate) clientKeyStore.getCertificate("cn=client"), clientCertFile); createTemporaryCertFile((X509Certificate) serverKeyStore.getCertificate("cn=server"), serverCertFile); createTemporaryCertFile((X509Certificate) untrustedKeyStore.getCertificate("cn=untrusted"), untrustedCertFile); createTemporaryKeyStoreFile(clientKeyStore, clientKeyFile); createTemporaryKeyStoreFile(clientTrustStore, clientTrustFile); createTemporaryKeyStoreFile(serverKeyStore, serverKeyFile); createTemporaryKeyStoreFile(serverTrustStore, serverTrustFile); createTemporaryKeyStoreFile(untrustedKeyStore, untrustedKeyFile); } /** The REDIRECT_STRATEGY for Apache HTTP Client */ public static final RedirectStrategy REDIRECT_STRATEGY = new DefaultRedirectStrategy() { @Override public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) { boolean isRedirect = false; try { isRedirect = super.isRedirected(request, response, context); } catch (ProtocolException e) { e.printStackTrace(); } if (!isRedirect) { final int responseCode = response.getStatusLine().getStatusCode(); isRedirect = (responseCode == 301 || responseCode == 302); } return isRedirect; } }; public static String hash(String target, String algorithm, Coding coding) { MessageDigest md = null; try { md = MessageDigest.getInstance(algorithm); } catch (Exception e) { e.printStackTrace(); } assert md != null; byte[] bytes = target.getBytes(StandardCharsets.UTF_8); byte[] byteHash = md.digest(bytes); String encodedHash; switch (coding) { case BASE_64: encodedHash = Base64.getEncoder().encodeToString(byteHash); break; case HEX: encodedHash = toHex(byteHash); break; default: throw new IllegalArgumentException("Unsuported coding:" + coding.name()); } return encodedHash; } public static String toHex(byte[] bytes) { StringBuilder sb = new StringBuilder(bytes.length * 2); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < bytes.length; i++) { byte b = bytes[i]; // top 4 bits char c = (char) ((b >> 4) & 0xf); if (c > 9) c = (char) ((c - 10) + 'a'); else c = (char) (c + '0'); sb.append(c); // bottom 4 bits c = (char) (b & 0xf); if (c > 9) c = (char) ((c - 10) + 'a'); else c = (char) (c + '0'); sb.append(c); } return sb.toString(); } public static URL getResource(String name) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); return tccl.getResource(name); } private static final long STOP_DELAY_DEFAULT = 0; /** * stops execution of the program indefinitely useful in testsuite debugging */ public static void stop() { stop(STOP_DELAY_DEFAULT); } /** * stop test execution for a given time interval useful for debugging * * @param delay interval (milliseconds), if delay<=0, interval is considered to be infinite (Long.MAX_VALUE) */ public static void stop(long delay) { long currentTime = System.currentTimeMillis(); long remainingTime = 0 < delay ? currentTime + delay - System.currentTimeMillis() : Long.MAX_VALUE; while (remainingTime > 0) { try { Thread.sleep(remainingTime); } catch (InterruptedException ex) { remainingTime = currentTime + delay - System.currentTimeMillis(); } } } public static void applyUpdates(final List<ModelNode> updates, final ModelControllerClient client) throws Exception { for (ModelNode update : updates) { applyUpdate(update, client); } } public static void applyUpdate(ModelNode update, final ModelControllerClient client) throws Exception { ModelNode result = client.execute(new OperationBuilder(update).build()); if (LOGGER.isInfoEnabled()) { LOGGER.trace("Client update: " + update); LOGGER.trace("Client update result: " + result); } if (result.hasDefined("outcome") && "success".equals(result.get("outcome").asString())) { LOGGER.debug("Operation succeeded."); } 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")); } } /** * Read the contents of an HttpResponse's entity and return it as a String. The content is converted using the character set * from the entity (if any), failing that, "ISO-8859-1" is used. * * @param response * @return * @throws IOException */ public static String getContent(HttpResponse response) throws IOException { return EntityUtils.toString(response.getEntity()); } /** * Makes HTTP call with FORM authentication. * * @param URL * @param user * @param pass * @param expectedStatusCode * @throws Exception */ public static void makeCall(String URL, String user, String pass, int expectedStatusCode) throws Exception { try (CloseableHttpClient httpClient = HttpClients.createDefault()){ HttpGet httpget = new HttpGet(URL); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { EntityUtils.consume(entity); } // We should get the Login Page StatusLine statusLine = response.getStatusLine(); assertEquals(200, statusLine.getStatusCode()); // We should now login with the user name and password HttpPost httpost = new HttpPost(URL + "/j_security_check"); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("j_username", user)); nvps.add(new BasicNameValuePair("j_password", pass)); httpost.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8)); response = httpClient.execute(httpost); entity = response.getEntity(); if (entity != null) { EntityUtils.consume(entity); } statusLine = response.getStatusLine(); // Post authentication - we have a 302 assertEquals(302, statusLine.getStatusCode()); Header locationHeader = response.getFirstHeader("Location"); String location = locationHeader.getValue(); HttpGet httpGet = new HttpGet(location); response = httpClient.execute(httpGet); entity = response.getEntity(); if (entity != null) { EntityUtils.consume(entity); } // Either the authentication passed or failed based on the expected status code statusLine = response.getStatusLine(); assertEquals(expectedStatusCode, statusLine.getStatusCode()); } } /** * Returns "secondary.test.address" system property if such exists. If not found, then there is a fallback to * {@link ManagementClient#getMgmtAddress()} or {@link #getDefaultHost(boolean)} (when mgmtClient is <code>null</code>). * Returned value can be converted to canonical hostname if useCanonicalHost==true. Returned value is not formatted for URLs * (i.e. square brackets are not placed around IPv6 addr - for instance "::1") * * @param mgmtClient management client instance (may be <code>null</code>) * @param useCanonicalHost * @return */ public static String getSecondaryTestAddress(final ManagementClient mgmtClient, final boolean useCanonicalHost) { String address = System.getProperty("secondary.test.address"); if (StringUtils.isBlank(address)) { address = mgmtClient != null ? mgmtClient.getMgmtAddress() : getDefaultHost(false); } if (useCanonicalHost) { address = getCannonicalHost(address); } return stripSquareBrackets(address); } /** * Returns "secondary.test.address" system property if such exists. If not found, then there is a fallback to * {@link ManagementClient#getMgmtAddress()}. Returned value is formatted to use in URLs (i.e. if it's IPv6 address, then * square brackets are placed around - e.g. "[::1]") * * @param mgmtClient management client instance (may be <code>null</code>) * @return */ public static String getSecondaryTestAddress(final ManagementClient mgmtClient) { return NetworkUtils.formatPossibleIpv6Address(getSecondaryTestAddress(mgmtClient, false)); } /** * Requests given URL and checks if the returned HTTP status code is the expected one. Returns HTTP response body * * @param url URL to which the request should be made * @param httpClient DefaultHttpClient to test multiple access * @param expectedStatusCode expected status code returned from the requested server * @return HTTP response body * @throws IOException * @throws URISyntaxException */ public static String makeCallWithHttpClient(URL url, HttpClient httpClient, int expectedStatusCode) throws 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; } /** * Returns response body for the given URL request as a String. It also checks if the returned HTTP status code is the * expected one. If the server returns {@link HttpServletResponse#SC_UNAUTHORIZED} and username is provided, then a new * request is created with the provided credentials (basic authentication). * * @param url URL to which the request should be made * @param user Username (may be null) * @param pass Password (may be null) * @param expectedStatusCode expected status code returned from the requested server * @return HTTP response body * @throws IOException * @throws URISyntaxException */ public static String makeCallWithBasicAuthn(URL url, String user, String pass, int expectedStatusCode) throws IOException, URISyntaxException { return makeCallWithBasicAuthn(url, user, pass, expectedStatusCode, false); } /** * Returns response body for the given URL request as a String. It also checks if the returned HTTP status code is the * expected one. If the server returns {@link HttpServletResponse#SC_UNAUTHORIZED} and username is provided, then a new * request is created with the provided credentials (basic authentication). * * @param url URL to which the request should be made * @param user Username (may be null) * @param pass Password (may be null) * @param expectedStatusCode expected status code returned from the requested server * @param checkFollowupAuthState whether to check auth state for followup request - if set to true, followup * request is sent to server and 200 OK is expected directly (no re-authentication * challenge - 401 Unauthorized - is expected) * @return HTTP response body * @throws IOException * @throws URISyntaxException */ public static String makeCallWithBasicAuthn(URL url, String user, String pass, int expectedStatusCode, boolean checkFollowupAuthState) throws IOException, URISyntaxException { LOGGER.trace("Requesting URL " + url); // use UTF-8 charset for credentials Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory(StandardCharsets.UTF_8)) .register(AuthSchemes.DIGEST, new DigestSchemeFactory(StandardCharsets.UTF_8)) .build(); try (CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultAuthSchemeRegistry(authSchemeRegistry) .build()){ final HttpGet httpGet = new HttpGet(url.toURI()); HttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) { assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode); return EntityUtils.toString(response.getEntity()); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user); } HttpEntity entity = response.getEntity(); if (entity != null) EntityUtils.consume(entity); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, pass); HttpClientContext hc = new HttpClientContext(); hc.setCredentialsProvider(new BasicCredentialsProvider()); hc.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), credentials); //enable auth response = httpClient.execute(httpGet, hc); statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode); if (checkFollowupAuthState) { // Let's disable authentication for this client as we already have all the context necessary to be // authorized (we expect that gained 'nonce' value can be re-used in our case here). // By disabling authentication we simply get first server response and thus we can check whether we've // got 200 OK or different response code. RequestConfig reqConf = RequestConfig.custom().setAuthenticationEnabled(false).build(); httpGet.setConfig(reqConf); response = httpClient.execute(httpGet, hc); statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code returned after the authentication.", HttpURLConnection.HTTP_OK, statusCode); } return EntityUtils.toString(response.getEntity()); } } /** * Do HTTP request using given client with BEARER_TOKEN authentication.The implementation makes 2 calls - the first without * Authorization header provided (just to check response code and WWW-Authenticate header value), the second with * Authorization header. * * @param url URL to make request to * @param token bearer token * @param expectedStatusCode expected status code * @return response body * @throws URISyntaxException * @throws UnsupportedEncodingException * @throws ClientProtocolException */ public static String makeCallWithTokenAuthn(final URL url, String token, int expectedStatusCode) throws URISyntaxException, IOException, ClientProtocolException { LOGGER.trace("Requesting URL: " + url); try (CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(REDIRECT_STRATEGY).build()) { final HttpGet httpGet = new HttpGet(url.toURI()); HttpResponse response = httpClient.execute(httpGet); assertEquals("Unexpected HTTP response status code.", SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); Header[] authenticateHeaders = response.getHeaders("WWW-Authenticate"); assertTrue("Expected WWW-Authenticate header was not present in the HTTP response", authenticateHeaders != null && authenticateHeaders.length > 0); boolean bearerAuthnHeaderFound = false; for (Header header : authenticateHeaders) { final String headerVal = header.getValue(); if (headerVal != null && headerVal.startsWith("Bearer")) { bearerAuthnHeaderFound = true; break; } } assertTrue("WWW-Authenticate response header didn't request expected Bearer token authentication", bearerAuthnHeaderFound); HttpEntity entity = response.getEntity(); if (entity != null) { EntityUtils.consume(entity); } if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("HTTP response was SC_UNAUTHORIZED, let's authenticate using the token '%s'", token)); } httpGet.addHeader("Authorization", "Bearer " + token); response = httpClient.execute(httpGet); assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, response.getStatusLine().getStatusCode()); return EntityUtils.toString(response.getEntity()); } } /** * Generates content of jboss-ejb3.xml file as a ShrinkWrap asset with the given security domain name. * * @param securityDomain security domain name * @return Asset instance */ public static Asset getJBossEjb3XmlAsset(final String securityDomain) { String sb = "<jboss:ejb-jar xmlns:jboss='http://www.jboss.com/xml/ns/javaee'" + "\n\txmlns='http://java.sun.com/xml/ns/javaee'" + "\n\txmlns:s='urn:security'" + "\n\tversion='3.1'" + "\n\timpl-version='2.0'>" + "\n\t<assembly-descriptor><s:security>" + "\n\t\t<ejb-name>*</ejb-name>" + "\n\t\t<s:security-domain>" + securityDomain + "</s:security-domain>" + "\n\t</s:security></assembly-descriptor>" + "\n</jboss:ejb-jar>"; return new StringAsset(sb); } /** * Generates content of jboss-web.xml file as a ShrinkWrap asset with the given security domain name and given valve class. * * @param securityDomain security domain name (not-<code>null</code>) * @param valveClassNames valve class (e.g. an Authenticator) which should be added to jboss-web file (may be * <code>null</code>) * @return Asset instance */ public static Asset getJBossWebXmlAsset(final String securityDomain, final String... valveClassNames) { final StringBuilder sb = new StringBuilder(); sb.append("<jboss-web>"); sb.append("\n\t<security-domain>").append(securityDomain).append("</security-domain>"); if (valveClassNames != null) { for (String valveClassName : valveClassNames) { if (StringUtils.isNotEmpty(valveClassName)) { sb.append("\n\t<valve><class-name>").append(valveClassName).append("</class-name></valve>"); } } } sb.append("\n</jboss-web>"); return new StringAsset(sb.toString()); } /** * Generates content of the jboss-deployment-structure.xml deployment descriptor as a ShrinkWrap asset. It fills the given * dependencies (module names) into it. * * @param dependencies AS module names * @return */ public static Asset getJBossDeploymentStructure(String... dependencies) { final StringBuilder sb = new StringBuilder(); sb.append("<jboss-deployment-structure><deployment><dependencies>"); if (dependencies != null) { for (String moduleName : dependencies) { sb.append("\n\t<module name='").append(moduleName).append("'/>"); } } sb.append("\n</dependencies></deployment></jboss-deployment-structure>"); return new StringAsset(sb.toString()); } /** * Creates content of users.properties and/or roles.properties files for given array of role names. * <p> * For instance if you provide 2 roles - "role1", "role2" then the result will be: * * <pre> * role1=role1 * role2=role2 * </pre> * * If you use it as users.properties and roles.properties, then <code>roleName == userName == password</code> * * @param roles role names (used also as user names and passwords) * @return not-<code>null</code> content of users.properties and/or roles.properties */ public static String createUsersFromRoles(String... roles) { final StringBuilder sb = new StringBuilder(); if (roles != null) { for (String role : roles) { sb.append(role).append("=").append(role).append("\n"); } } return sb.toString(); } /** * Strips square brackets - '[' and ']' from the given string. It can be used for instance to remove the square brackets * around IPv6 address in a URL. * * @param str string to strip * @return str without square brackets in it */ public static String stripSquareBrackets(final String str) { return StringUtils.strip(str, "[]"); } /** * Fixes/replaces LDAP bind address in the CreateTransport annotation of ApacheDS. * * @param createLdapServer * @param address */ public static void fixApacheDSTransportAddress(ManagedCreateLdapServer createLdapServer, String address) { final CreateTransport[] createTransports = createLdapServer.transports(); for (int i = 0; i < createTransports.length; i++) { final ManagedCreateTransport mgCreateTransport = new ManagedCreateTransport(createTransports[i]); // localhost is a default used in original CreateTransport annotation. We use it as a fallback. mgCreateTransport.setAddress(address != null ? address : "localhost"); createTransports[i] = mgCreateTransport; } } /** * Copies server and clients keystores and truststores from this package to the given folder. Server truststore has accepted * certificate from client keystore and vice-versa * * @param workingFolder folder to which key material should be copied * @throws IOException copying of keystores fails * @throws IllegalArgumentException workingFolder is null or it's not a directory */ public static void createKeyMaterial(final File workingFolder) throws IOException, IllegalArgumentException { if (workingFolder == null || !workingFolder.isDirectory()) { throw new IllegalArgumentException("Provide an existing folder as the method parameter."); } try { generateKeyMaterial(workingFolder); } catch (IOException | IllegalArgumentException e) { throw e; } catch (Exception e) { throw new RuntimeException("Unable to generate key material"); } LOGGER.trace("Key material created in " + workingFolder.getAbsolutePath()); } /** * Makes HTTP call without authentication. Returns response body as a String. * * @param uri requested URL * @param expectedStatusCode expected status code - it's checked after the request is executed * @throws Exception */ public static String makeCall(URI uri, int expectedStatusCode) throws Exception { try (CloseableHttpClient httpClient = HttpClients.createDefault()){ final HttpGet httpget = new HttpGet(uri); final HttpResponse response = httpClient.execute(httpget); int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code in HTTP response.", expectedStatusCode, statusCode); return EntityUtils.toString(response.getEntity()); } } /** * Returns param/value pair in form "urlEncodedName=urlEncodedValue". It can be used for instance in HTTP get queries. * * @param paramName parameter name * @param paramValue parameter value * @return "[urlEncodedName]=[urlEncodedValue]" string */ public static String encodeQueryParam(final String paramName, final String paramValue) { return StringUtils.isEmpty(paramValue) ? null : (URLEncoder.encode(paramName, StandardCharsets.UTF_8) + "=" + URLEncoder.encode( StringUtils.defaultString(paramValue, StringUtils.EMPTY), StandardCharsets.UTF_8)); } /** * Returns management address (host) from the givem {@link ManagementClient}. If the * returned value is IPv6 address then square brackets around are stripped. * * @param managementClient * @return */ public static String getHost(final ManagementClient managementClient) { return CoreUtils.stripSquareBrackets(managementClient.getMgmtAddress()); } /** * Returns hostname - either read from the "node0" system property or the loopback address "127.0.0.1". * * @param canonical return hostname in canonical form * * @return */ public static String getDefaultHost(boolean canonical) { final String hostname = TestSuiteEnvironment.getHttpAddress(); return canonical ? getCannonicalHost(hostname) : hostname; } /** * Returns installed login configuration. * * @return Configuration */ public static Configuration getLoginConfiguration() { Configuration configuration = null; try { configuration = Configuration.getConfiguration(); } catch (SecurityException e) { LOGGER.debug("Unable to load default login configuration", e); } return configuration; } /** * Creates login context for given {@link Krb5LoginConfiguration} and credentials and calls the {@link LoginContext#login()} * method on it. This method contains workaround for IBM JDK issue described in bugzilla <a * href="https://bugzilla.redhat.com/show_bug.cgi?id=1206177">https://bugzilla.redhat.com/show_bug.cgi?id=1206177</a>. * * @param krb5Configuration * @param user * @param pass * @return * @throws LoginException */ public static LoginContext loginWithKerberos(final Krb5LoginConfiguration krb5Configuration, final String user, final String pass) throws LoginException { LoginContext lc = new LoginContext(krb5Configuration.getName(), new UsernamePasswordCBH(user, pass.toCharArray())); lc.login(); return lc; } /** * Creates a temporary folder name with given name prefix. * * @param prefix folder name prefix * @return created folder */ @SuppressWarnings("ResultOfMethodCallIgnored") public static File createTemporaryFolder(String prefix) throws IOException { File file = File.createTempFile(prefix, "", null); LOGGER.debugv("Creating temporary folder {0}", file); file.delete(); file.mkdir(); return file; } private static class UsernamePasswordCBH implements CallbackHandler { /* * Note: We use CallbackHandler implementations like this in test cases as test cases need to run unattended, a true * CallbackHandler implementation should interact directly with the current user to prompt for the username and * password. * * i.e. In a client app NEVER prompt for these values in advance and provide them to a CallbackHandler like this. */ private final String username; private final char[] password; private UsernamePasswordCBH(final String username, final char[] password) { this.username = username; this.password = password; } @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (Callback current : callbacks) { if (current instanceof NameCallback) { NameCallback ncb = (NameCallback) current; ncb.setName(username); } else if (current instanceof PasswordCallback) { PasswordCallback pcb = (PasswordCallback) current; pcb.setPassword(password); } else { throw new UnsupportedCallbackException(current); } } } } }
36,987
43.033333
156
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/AbstractDataSourceServerSetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.security.common; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; 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 java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.security.common.config.DataSource; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; /** * {@link ServerSetupTask} instance for datasources setup. * * @author Josef Cacek */ public abstract class AbstractDataSourceServerSetupTask extends SnapshotRestoreSetupTask { private static final Logger LOGGER = Logger.getLogger(AbstractDataSourceServerSetupTask.class); private static final String SUBSYSTEM_DATASOURCES = "datasources"; private static final String DATASOURCE = "data-source"; // Public methods -------------------------------------------------------- /** * Adds a security domain represented by this class to the AS configuration. * * @param managementClient * @param containerId * @throws Exception * @see ServerSetupTask#setup(ManagementClient, * String) */ public final void doSetup(final ManagementClient managementClient, String containerId) throws Exception { final DataSource[] dataSourceConfigurations = getDataSourceConfigurations(managementClient, containerId); if (dataSourceConfigurations == null) { LOGGER.warn("Null DataSourceConfiguration array provided"); return; } final List<ModelNode> updates = new ArrayList<ModelNode>(); for (final DataSource config : dataSourceConfigurations) { final String name = config.getName(); LOGGER.trace("Adding datasource " + name); final ModelNode dsNode = new ModelNode(); dsNode.get(OP).set(ADD); dsNode.get(OP_ADDR).add(SUBSYSTEM, SUBSYSTEM_DATASOURCES); dsNode.get(OP_ADDR).add(DATASOURCE, name); dsNode.get("connection-url").set(config.getConnectionUrl()); dsNode.get("jndi-name").set(config.getJndiName()); dsNode.get("driver-name").set(config.getDriver()); dsNode.get("enabled").set("false"); if (StringUtils.isNotEmpty(config.getUsername())) { dsNode.get("user-name").set(config.getUsername()); } if (StringUtils.isNotEmpty(config.getPassword())) { dsNode.get("password").set(config.getPassword()); } updates.add(dsNode); final ModelNode enableNode = new ModelNode(); enableNode.get("name").set("enabled"); enableNode.get("value").set(true); enableNode.get(OP).set("write-attribute"); enableNode.get(OP_ADDR).add(SUBSYSTEM, SUBSYSTEM_DATASOURCES); enableNode.get(OP_ADDR).add(DATASOURCE, name); updates.add(enableNode); } CoreUtils.applyUpdates(updates, managementClient.getControllerClient()); ServerReload.executeReloadAndWaitForCompletion(managementClient, 50000); } // Protected methods ----------------------------------------------------- protected DataSource[] getDataSourceConfigurations(final ManagementClient managementClient, String containerId) { return null; } }
4,813
43.165138
117
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/ManagedCreateLdapServer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.security.common; import jakarta.enterprise.util.AnnotationLiteral; import org.apache.directory.server.annotations.CreateLdapServer; import org.apache.directory.server.annotations.CreateTransport; import org.apache.directory.server.annotations.SaslMechanism; /** * A helper implementation of {@link CreateLdapServer} annotation which allows to configure values. * * @author Josef Cacek */ public class ManagedCreateLdapServer extends AnnotationLiteral<CreateLdapServer> implements CreateLdapServer { private static final long serialVersionUID = 1L; /** The instance name */ private String name; /** The transports to use, default to LDAP */ private CreateTransport[] transports; /** The LdapServer factory */ private Class<?> factory; /** The maximum size limit. */ private long maxSizeLimit; /** The maximum time limit. */ private int maxTimeLimit; /** Tells if anonymous access are allowed or not. */ private boolean allowAnonymousAccess; /** The external keyStore file to use, default to the empty string */ private String keyStore; /** The certificate password in base64, default to the empty string */ private String certificatePassword; /** name of the classes implementing extended operations */ private Class<?>[] extendedOpHandlers; /** supported set of SASL mechanisms */ private SaslMechanism[] saslMechanisms; /** NTLM provider class, default value is an invalid class */ private Class<?> ntlmProvider; /** The name of this host, validated during SASL negotiation. */ private String saslHost; /** The service principal, used by GSSAPI. */ private String saslPrincipal; /** The service principal, used by GSSAPI. */ private String[] saslRealms; // Constructors ---------------------------------------------------------- /** * Create a new ManagedCreateLdapServer. * * @param createLdapServer */ public ManagedCreateLdapServer(CreateLdapServer createLdapServer) { name = createLdapServer.name(); transports = createLdapServer.transports(); factory = createLdapServer.factory(); maxSizeLimit = createLdapServer.maxSizeLimit(); maxTimeLimit = createLdapServer.maxTimeLimit(); allowAnonymousAccess = createLdapServer.allowAnonymousAccess(); keyStore = createLdapServer.keyStore(); certificatePassword = createLdapServer.certificatePassword(); extendedOpHandlers = createLdapServer.extendedOpHandlers(); saslMechanisms = createLdapServer.saslMechanisms(); ntlmProvider = createLdapServer.ntlmProvider(); saslHost = createLdapServer.saslHost(); saslPrincipal = createLdapServer.saslPrincipal(); saslRealms = createLdapServer.saslRealms(); } // Public methods -------------------------------------------------------- /** * * @return * @see CreateLdapServer#name() */ public String name() { return name; } /** * * @return * @see CreateLdapServer#transports() */ public CreateTransport[] transports() { return transports; } /** * * @return * @see CreateLdapServer#factory() */ public Class<?> factory() { return factory; } /** * * @return * @see CreateLdapServer#maxSizeLimit() */ public long maxSizeLimit() { return maxSizeLimit; } /** * * @return * @see CreateLdapServer#maxTimeLimit() */ public int maxTimeLimit() { return maxTimeLimit; } /** * * @return * @see CreateLdapServer#allowAnonymousAccess() */ public boolean allowAnonymousAccess() { return allowAnonymousAccess; } /** * * @return * @see CreateLdapServer#keyStore() */ public String keyStore() { return keyStore; } /** * * @return * @see CreateLdapServer#certificatePassword() */ public String certificatePassword() { return certificatePassword; } /** * * @return * @see CreateLdapServer#extendedOpHandlers() */ public Class<?>[] extendedOpHandlers() { return extendedOpHandlers; } /** * * @return * @see CreateLdapServer#saslMechanisms() */ public SaslMechanism[] saslMechanisms() { return saslMechanisms; } /** * * @return * @see CreateLdapServer#ntlmProvider() */ public Class<?> ntlmProvider() { return ntlmProvider; } /** * * @return * @see CreateLdapServer#saslHost() */ public String saslHost() { return saslHost; } /** * * @return * @see CreateLdapServer#saslPrincipal() */ public String saslPrincipal() { return saslPrincipal; } @Override public String[] saslRealms() { return saslRealms; } /** * Set the name. * * @param name The name to set. */ public void setName(String name) { this.name = name; } /** * Set the transports. * * @param transports The transports to set. */ public void setTransports(CreateTransport[] transports) { this.transports = transports; } /** * Set the factory. * * @param factory The factory to set. */ public void setFactory(Class<?> factory) { this.factory = factory; } /** * Set the maxSizeLimit. * * @param maxSizeLimit The maxSizeLimit to set. */ public void setMaxSizeLimit(long maxSizeLimit) { this.maxSizeLimit = maxSizeLimit; } /** * Set the maxTimeLimit. * * @param maxTimeLimit The maxTimeLimit to set. */ public void setMaxTimeLimit(int maxTimeLimit) { this.maxTimeLimit = maxTimeLimit; } /** * Set the allowAnonymousAccess. * * @param allowAnonymousAccess The allowAnonymousAccess to set. */ public void setAllowAnonymousAccess(boolean allowAnonymousAccess) { this.allowAnonymousAccess = allowAnonymousAccess; } /** * Set the keyStore. * * @param keyStore The keyStore to set. */ public void setKeyStore(String keyStore) { this.keyStore = keyStore; } /** * Set the certificatePassword. * * @param certificatePassword The certificatePassword to set. */ public void setCertificatePassword(String certificatePassword) { this.certificatePassword = certificatePassword; } /** * Set the extendedOpHandlers. * * @param extendedOpHandlers The extendedOpHandlers to set. */ public void setExtendedOpHandlers(Class<?>[] extendedOpHandlers) { this.extendedOpHandlers = extendedOpHandlers; } /** * Set the saslMechanisms. * * @param saslMechanisms The saslMechanisms to set. */ public void setSaslMechanisms(SaslMechanism[] saslMechanisms) { this.saslMechanisms = saslMechanisms; } /** * Set the ntlmProvider. * * @param ntlmProvider The ntlmProvider to set. */ public void setNtlmProvider(Class<?> ntlmProvider) { this.ntlmProvider = ntlmProvider; } /** * Set the saslHost. * * @param saslHost The saslHost to set. */ public void setSaslHost(String saslHost) { this.saslHost = saslHost; } /** * Set the saslPrincipal. * * @param saslPrincipal The saslPrincipal to set. */ public void setSaslPrincipal(String saslPrincipal) { this.saslPrincipal = saslPrincipal; } }
8,800
25.193452
110
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/ManagedCreateTransport.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.security.common; import jakarta.enterprise.util.AnnotationLiteral; import org.apache.directory.server.annotations.CreateTransport; import org.apache.directory.server.annotations.TransportType; /** * A helper implementation of {@link CreateTransport} annotation which allows to configure values. * * @author Josef Cacek */ public class ManagedCreateTransport extends AnnotationLiteral<CreateTransport> implements CreateTransport { private static final long serialVersionUID = 1L; /** The name for this protocol */ private String protocol; /** The transport type (TCP or UDP) Default to TCP */ private TransportType type; /** The port to use, default to a bad value so that we know we have to pick one random available port */ private int port; /** The InetAddress for this transport. Default to localhost */ private String address; /** The backlog. Default to 50 */ private int backlog; /** A flag to tell if the transport is SSL based. Default to false */ private boolean ssl; /** The number of threads to use. Default to 3 */ private int nbThreads; /** A flag to tell if the transport should ask for client certificate. Default to false */ private boolean clientAuth; // Constructors ---------------------------------------------------------- /** * Create a new ManagedCreateTransport. * * @param createLdapServer */ public ManagedCreateTransport(final CreateTransport original) { protocol = original.protocol(); type = original.type(); port = original.port(); address = original.address(); backlog = original.backlog(); ssl = original.ssl(); nbThreads = original.nbThreads(); clientAuth = original.clientAuth(); } // Public methods -------------------------------------------------------- /** * * @return * @see CreateTransport#protocol() */ public String protocol() { return protocol; } /** * * @return * @see CreateTransport#type() */ public TransportType type() { return type; } /** * * @return * @see CreateTransport#port() */ public int port() { return port; } /** * * @return * @see CreateTransport#address() */ public String address() { return address; } /** * * @return * @see CreateTransport#backlog() */ public int backlog() { return backlog; } /** * * @return * @see CreateTransport#ssl() */ public boolean ssl() { return ssl; } /** * * @return * @see CreateTransport#nbThreads() */ public int nbThreads() { return nbThreads; } @Override public boolean clientAuth() { return clientAuth; } /** * Set the protocol. * * @param protocol The protocol to set. */ public void setProtocol(String protocol) { this.protocol = protocol; } /** * Set the type. * * @param type The type to set. */ public void setType(TransportType type) { this.type = type; } /** * Set the port. * * @param port The port to set. */ public void setPort(int port) { this.port = port; } /** * Set the address. * * @param address The address to set. */ public void setAddress(String address) { this.address = address; } /** * Set the backlog. * * @param backlog The backlog to set. */ public void setBacklog(int backlog) { this.backlog = backlog; } /** * Set the ssl. * * @param ssl The ssl to set. */ public void setSsl(boolean ssl) { this.ssl = ssl; } /** * Set the nbThreads. * * @param nbThreads The nbThreads to set. */ public void setNbThreads(int nbThreads) { this.nbThreads = nbThreads; } public void setClientAuth(boolean clientAuth) { this.clientAuth = clientAuth; } }
5,214
23.952153
108
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/NullHCCredentials.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.security.common; import java.security.Principal; import org.apache.http.auth.Credentials; /** * An empty Apache HTTPClient {@link Credentials} implementation, used for SPNEGO authentications. * * @author Josef Cacek */ public class NullHCCredentials implements Credentials { // Public methods -------------------------------------------------------- /** * Returns <code>null</code> as the Principal. * * @return * @see Credentials#getUserPrincipal() */ public Principal getUserPrincipal() { return null; } /** * Returns <code>null</code> as the password. * * @return * @see Credentials#getPassword() */ public String getPassword() { return null; } }
1,815
30.859649
98
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/AbstractSystemPropertiesServerSetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.security.common; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; 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.REMOVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SYSTEM_PROPERTY; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; /** * {@link ServerSetupTask} instance for system properties setup. * * @author Josef Cacek */ public abstract class AbstractSystemPropertiesServerSetupTask implements ServerSetupTask { private static final Logger LOGGER = Logger.getLogger(AbstractSystemPropertiesServerSetupTask.class); private SystemProperty[] systemProperties; // Public methods -------------------------------------------------------- public final void setup(final ManagementClient managementClient, String containerId) throws Exception { if (LOGGER.isInfoEnabled()) { LOGGER.trace("Adding system properties."); } systemProperties = getSystemProperties(); if (systemProperties == null || systemProperties.length == 0) { LOGGER.warn("No system property configured in the ServerSetupTask"); return; } final List<ModelNode> updates = new ArrayList<ModelNode>(); for (SystemProperty systemProperty : systemProperties) { final String propertyName = systemProperty.getName(); if (propertyName == null || propertyName.trim().length() == 0) { LOGGER.warn("Empty property name provided."); continue; } ModelNode op = new ModelNode(); op.get(OP).set(ADD); op.get(OP_ADDR).add(SYSTEM_PROPERTY, propertyName); op.get(ModelDescriptionConstants.VALUE).set(systemProperty.getValue()); updates.add(op); } CoreUtils.applyUpdates(updates, managementClient.getControllerClient()); } /** * * @param managementClient * @param containerId * @see AbstractSecurityDomainSetup#tearDown(ManagementClient, * String) */ public final void tearDown(ManagementClient managementClient, String containerId) throws Exception { if (LOGGER.isInfoEnabled()) { LOGGER.trace("Removing system properties."); } if (systemProperties == null || systemProperties.length == 0) { return; } final List<ModelNode> updates = new ArrayList<ModelNode>(); for (SystemProperty systemProperty : systemProperties) { final String propertyName = systemProperty.getName(); if (propertyName == null || propertyName.trim().length() == 0) { continue; } ModelNode op = new ModelNode(); op.get(OP).set(REMOVE); op.get(OP_ADDR).add(SYSTEM_PROPERTY, propertyName); updates.add(op); } CoreUtils.applyUpdates(updates, managementClient.getControllerClient()); } public static SystemProperty[] mapToSystemProperties(Map<String, String> map) { if (map == null || map.isEmpty()) { return null; } final List<SystemProperty> list = new ArrayList<SystemProperty>(); for (Map.Entry<String, String> property : map.entrySet()) { list.add(new DefaultSystemProperty(property.getKey(), property.getValue())); } return list.toArray(new SystemProperty[list.size()]); } // Protected methods ----------------------------------------------------- /** * Returns configuration of the login modules. * * @return */ protected abstract SystemProperty[] getSystemProperties(); // Embedded classes ------------------------------------------------------ public interface SystemProperty { String getName(); String getValue(); } public static class DefaultSystemProperty implements SystemProperty { private final String name; private final String value; /** * Create a new DefaultSystemProperty. * * @param name * @param value */ public DefaultSystemProperty(String name, String value) { super(); this.name = name; this.value = value; } /** * Get the name. * * @return the name. */ public String getName() { return name; } /** * Get the value. * * @return the value. */ public String getValue() { return value; } } }
6,153
33.965909
107
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/AbstractSecurityDomainsServerSetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.security.common; 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.COMPOSITE; 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.ROLLBACK_ON_RUNTIME_FAILURE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.security.Constants.AUTH_MODULE; import static org.jboss.as.security.Constants.CLASSIC; import static org.jboss.as.security.Constants.FLAG; import static org.jboss.as.security.Constants.JSSE; import static org.jboss.as.security.Constants.KEYSTORE; import static org.jboss.as.security.Constants.LOGIN_MODULE; import static org.jboss.as.security.Constants.MODULE_OPTIONS; import static org.jboss.as.security.Constants.PASSWORD; import static org.jboss.as.security.Constants.SECURITY_DOMAIN; import static org.jboss.as.security.Constants.TRUSTSTORE; import static org.jboss.as.security.Constants.TYPE; import static org.jboss.as.security.Constants.URL; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.security.common.config.AuthnModule; import org.jboss.as.test.integration.security.common.config.JSSE; import org.jboss.as.test.integration.security.common.config.JaspiAuthn; import org.jboss.as.test.integration.security.common.config.LoginModuleStack; 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.shared.ServerReload; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; /** * {@link ServerSetupTask} instance for security domain setup. It supports JSSE configuration, JASPI authentication * configuration and stacks of login-modules (classic authentication), policy-modules and (role-)mapping-modules. * * @author Josef Cacek */ public abstract class AbstractSecurityDomainsServerSetupTask implements ServerSetupTask { private static final Logger LOGGER = Logger.getLogger(AbstractSecurityDomainsServerSetupTask.class); /** * The type attribute value of mapping-modules used for role assignment. */ private static final String ROLE = "role"; /** * The SUBSYSTEM_SECURITY */ private static final String SUBSYSTEM_SECURITY = "security"; protected ManagementClient managementClient; private SecurityDomain[] securityDomains; // Public methods -------------------------------------------------------- /** * Adds a security domain represented by this class to the AS configuration. * * @param managementClient * @param containerId * @throws Exception * @see ServerSetupTask#setup(ManagementClient, * String) */ public final void setup(final ManagementClient managementClient, String containerId) throws Exception { this.managementClient = managementClient; securityDomains = getSecurityDomains(); if (securityDomains == null || securityDomains.length == 0) { LOGGER.warn("Empty security domain configuration."); return; } // TODO remove this once security domains expose their own capability // Currently subsystem=security-domain exposes one, but the individual domains don't // which with WFCORE-1106 has the effect that any individual sec-domain op that puts // the server in reload-required means all ops for any sec-domain won't execute Stage.RUNTIME // So, for now we preemptively reload if needed ServerReload.BeforeSetupTask.INSTANCE.setup(managementClient, containerId); final List<ModelNode> updates = new LinkedList<ModelNode>(); for (final SecurityDomain securityDomain : securityDomains) { final String securityDomainName = securityDomain.getName(); if (LOGGER.isInfoEnabled()) { LOGGER.trace("Adding security domain " + securityDomainName); } final ModelNode compositeOp = new ModelNode(); compositeOp.get(OP).set(COMPOSITE); compositeOp.get(OP_ADDR).setEmptyList(); ModelNode steps = compositeOp.get(STEPS); PathAddress opAddr = PathAddress.pathAddress() .append(SUBSYSTEM, SUBSYSTEM_SECURITY) .append(SECURITY_DOMAIN, securityDomainName); ModelNode op = Util.createAddOperation(opAddr); if (StringUtils.isNotEmpty(securityDomain.getCacheType())) { op.get(Constants.CACHE_TYPE).set(securityDomain.getCacheType()); } steps.add(op); //only one can occur - authenticationType or authenticationJaspiType final boolean authNodeAdded = createSecurityModelNode(Constants.AUTHENTICATION, LOGIN_MODULE, FLAG, Constants.REQUIRED, securityDomain.getLoginModules(), securityDomainName, steps); if (!authNodeAdded) { final List<ModelNode> jaspiAuthnNodes = createJaspiAuthnNodes(securityDomain.getJaspiAuthn(), securityDomain.getName()); if (jaspiAuthnNodes != null) { for (ModelNode node : jaspiAuthnNodes) { steps.add(node); } } } createSecurityModelNode(Constants.AUTHORIZATION, Constants.POLICY_MODULE, FLAG, Constants.REQUIRED, securityDomain.getAuthorizationModules(), securityDomainName, steps); createSecurityModelNode(Constants.MAPPING, Constants.MAPPING_MODULE, TYPE, ROLE, securityDomain.getMappingModules(), securityDomainName, steps); final ModelNode jsseNode = createJSSENode(securityDomain.getJsse(), securityDomain.getName()); if (jsseNode != null) { steps.add(jsseNode); } updates.add(compositeOp); } CoreUtils.applyUpdates(updates, managementClient.getControllerClient()); } /** * Removes the security domain from the AS configuration. * * @param managementClient * @param containerId * @see AbstractSecurityDomainSetup#tearDown(ManagementClient, * String) */ public final void tearDown(ManagementClient managementClient, String containerId) throws Exception { if (securityDomains == null || securityDomains.length == 0) { LOGGER.warn("Empty security domain configuration."); return; } final List<ModelNode> updates = new ArrayList<ModelNode>(); for (final SecurityDomain securityDomain : securityDomains) { final String domainName = securityDomain.getName(); if (LOGGER.isInfoEnabled()) { LOGGER.trace("Removing security domain " + domainName); } final ModelNode op = new ModelNode(); op.get(OP).set(REMOVE); op.get(OP_ADDR).add(SUBSYSTEM, "security"); op.get(OP_ADDR).add(SECURITY_DOMAIN, domainName); // Don't rollback when the AS detects the war needs the module op.get(OPERATION_HEADERS, ROLLBACK_ON_RUNTIME_FAILURE).set(false); op.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true); updates.add(op); } CoreUtils.applyUpdates(updates, managementClient.getControllerClient()); this.managementClient = null; } // Protected methods ----------------------------------------------------- /** * Returns configuration for creating security domains. * * @return array of SecurityDomain */ protected abstract SecurityDomain[] getSecurityDomains() throws Exception; // Private methods ------------------------------------------------------- /** * Creates authenticaton=>jaspi node and its child nodes. * * @param securityConfigurations * @return */ private List<ModelNode> createJaspiAuthnNodes(JaspiAuthn securityConfigurations, String domainName) { if (securityConfigurations == null) { LOGGER.trace("No security configuration for JASPI module."); return null; } if (securityConfigurations.getAuthnModules() == null || securityConfigurations.getAuthnModules().length == 0 || securityConfigurations.getLoginModuleStacks() == null || securityConfigurations.getLoginModuleStacks().length == 0) { throw new IllegalArgumentException("Missing mandatory part of JASPI configuration in the security domain."); } final List<ModelNode> steps = new ArrayList<ModelNode>(); PathAddress domainAddress = PathAddress.pathAddress() .append(SUBSYSTEM, SUBSYSTEM_SECURITY) .append(SECURITY_DOMAIN, domainName); PathAddress jaspiAddress = domainAddress.append(Constants.AUTHENTICATION, Constants.JASPI); steps.add(Util.createAddOperation(jaspiAddress)); for (final AuthnModule config : securityConfigurations.getAuthnModules()) { LOGGER.trace("Adding auth-module: " + config); final ModelNode securityModuleNode = Util.createAddOperation(jaspiAddress.append(AUTH_MODULE,config.getName())); steps.add(securityModuleNode); securityModuleNode.get(ModelDescriptionConstants.CODE).set(config.getName()); if (config.getFlag() != null) { securityModuleNode.get(FLAG).set(config.getFlag()); } if (config.getModule() != null) { securityModuleNode.get(Constants.MODULE).set(config.getModule()); } if (config.getLoginModuleStackRef() != null) { securityModuleNode.get(Constants.LOGIN_MODULE_STACK_REF).set(config.getLoginModuleStackRef()); } Map<String, String> configOptions = config.getOptions(); if (configOptions == null) { LOGGER.trace("No module options provided."); configOptions = Collections.emptyMap(); } final ModelNode moduleOptionsNode = securityModuleNode.get(MODULE_OPTIONS); for (final Map.Entry<String, String> entry : configOptions.entrySet()) { final String optionName = entry.getKey(); final String optionValue = entry.getValue(); moduleOptionsNode.add(optionName, optionValue); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Adding module option [" + optionName + "=" + optionValue + "]"); } } } //Unable to use securityComponentNode.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true) because the login-module-stack is empty for (final LoginModuleStack lmStack : securityConfigurations.getLoginModuleStacks()) { PathAddress lmStackAddress = jaspiAddress.append(Constants.LOGIN_MODULE_STACK, lmStack.getName()); steps.add(Util.createAddOperation(lmStackAddress)); for (final SecurityModule config : lmStack.getLoginModules()) { final String code = config.getName(); final ModelNode securityModuleNode = Util.createAddOperation(lmStackAddress.append(LOGIN_MODULE, code)); final String flag = StringUtils.defaultIfEmpty(config.getFlag(), Constants.REQUIRED); securityModuleNode.get(ModelDescriptionConstants.CODE).set(code); securityModuleNode.get(FLAG).set(flag); if (LOGGER.isInfoEnabled()) { LOGGER.trace("Adding JASPI login module stack [code=" + code + ", flag=" + flag + "]"); } Map<String, String> configOptions = config.getOptions(); if (configOptions == null) { LOGGER.trace("No module options provided."); configOptions = Collections.emptyMap(); } final ModelNode moduleOptionsNode = securityModuleNode.get(MODULE_OPTIONS); for (final Map.Entry<String, String> entry : configOptions.entrySet()) { final String optionName = entry.getKey(); final String optionValue = entry.getValue(); moduleOptionsNode.add(optionName, optionValue); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Adding module option [" + optionName + "=" + optionValue + "]"); } } securityModuleNode.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true); steps.add(securityModuleNode); } } return steps; } /** * Creates a {@link ModelNode} with the security component configuration. If the securityConfigurations array is empty or * null, then null is returned. * * @param securityComponent name of security component (e.g. {@link Constants#AUTHORIZATION}) * @param subnodeName name of the security component subnode, which holds module configurations (e.g. * {@link Constants#POLICY_MODULES}) * @param flagAttributeName name of attribute to which the value of {@link SecurityModule#getFlag()} is set * @param flagDefaultValue default value for flagAttributeName attr. * @param securityModules configurations * @return ModelNode instance or null */ private boolean createSecurityModelNode(String securityComponent, String subnodeName, String flagAttributeName, String flagDefaultValue, final SecurityModule[] securityModules, String domainName, ModelNode operations) { if (securityModules == null || securityModules.length == 0) { if (LOGGER.isInfoEnabled()) { LOGGER.trace("No security configuration for " + securityComponent + " module."); } return false; } PathAddress address = PathAddress.pathAddress() .append(SUBSYSTEM, SUBSYSTEM_SECURITY) .append(SECURITY_DOMAIN, domainName) .append(securityComponent, CLASSIC); operations.add(Util.createAddOperation(address)); for (final SecurityModule config : securityModules) { final String code = config.getName(); final ModelNode securityModuleNode = Util.createAddOperation(address.append(subnodeName, code)); final String flag = StringUtils.defaultIfEmpty(config.getFlag(), flagDefaultValue); securityModuleNode.get(ModelDescriptionConstants.CODE).set(code); securityModuleNode.get(flagAttributeName).set(flag); Map<String, String> configOptions = config.getOptions(); if (configOptions == null) { LOGGER.trace("No module options provided."); configOptions = Collections.emptyMap(); } if (LOGGER.isInfoEnabled()) { LOGGER.trace("Adding " + securityComponent + " module [code=" + code + ", " + flagAttributeName + "=" + flag + ", options = " + configOptions + "]"); } final ModelNode moduleOptionsNode = securityModuleNode.get(MODULE_OPTIONS); for (final Map.Entry<String, String> entry : configOptions.entrySet()) { final String optionName = entry.getKey(); final String optionValue = entry.getValue(); moduleOptionsNode.add(optionName, optionValue); } securityModuleNode.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true); operations.add(securityModuleNode); } return true; } /** * Creates a {@link ModelNode} with configuration of the JSSE part of security domain. * * @param jsse * @param domainName * @return */ private ModelNode createJSSENode(final JSSE jsse, String domainName) { if (jsse == null) { if (LOGGER.isInfoEnabled()) { LOGGER.trace("No security configuration for JSSE module."); } return null; } final ModelNode securityComponentNode = new ModelNode(); securityComponentNode.get(OP).set(ADD); securityComponentNode.get(OP_ADDR).add(SUBSYSTEM, SUBSYSTEM_SECURITY); securityComponentNode.get(OP_ADDR).add(SECURITY_DOMAIN, domainName); securityComponentNode.get(OP_ADDR).add(JSSE, CLASSIC); addSecureStore(jsse.getTrustStore(), TRUSTSTORE, securityComponentNode); addSecureStore(jsse.getKeyStore(), KEYSTORE, securityComponentNode); securityComponentNode.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true); return securityComponentNode; } /** * Adds given secureStore to a JSSE configuration represented by given ModelNode. * * @param secureStore * @param storeName * @param jsseNode */ private void addSecureStore(SecureStore secureStore, String storeName, ModelNode jsseNode) { if (secureStore == null) { return; } if (secureStore.getUrl() != null) { jsseNode.get(storeName, URL).set(secureStore.getUrl().toExternalForm()); } if (secureStore.getPassword() != null) { jsseNode.get(storeName, PASSWORD).set(secureStore.getPassword()); } if (secureStore.getType() != null) { jsseNode.get(storeName, TYPE).set(secureStore.getType()); } } }
19,750
47.888614
181
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/AbstractSecurityDomainSetup.java
package org.jboss.as.test.integration.security.common; import java.io.IOException; import java.util.List; import org.jboss.as.arquillian.api.ServerSetupTask; 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 Stuart Douglas */ public abstract class AbstractSecurityDomainSetup implements ServerSetupTask { private static final Logger LOGGER = Logger.getLogger(AbstractSecurityDomainSetup.class); protected static void applyUpdates(final ModelControllerClient client, final List<ModelNode> updates) { for (ModelNode update : updates) { try { applyUpdate(client, update, false); } catch (Exception e) { throw new RuntimeException(e); } } } protected static void applyUpdate(final ModelControllerClient client, ModelNode update, boolean allowFailure) throws IOException { ModelNode result = client.execute(new OperationBuilder(update).build()); if (result.hasDefined("outcome") && (allowFailure || "success".equals(result.get("outcome").asString()))) { if (result.hasDefined("result")) { LOGGER.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")); } } protected abstract String getSecurityDomainName(); }
1,676
37.113636
134
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/Krb5LoginConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.security.common; import java.io.File; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import java.util.UUID; import javax.security.auth.login.AppConfigurationEntry; import javax.security.auth.login.Configuration; /** * Simple Krb5LoginModule configuration. * * @author Josef Cacek */ public class Krb5LoginConfiguration extends Configuration { /** The list with configuration entries. */ private final AppConfigurationEntry[] configList = new AppConfigurationEntry[1]; private final String name; private final Configuration wrapped; /** * Create a new Krb5LoginConfiguration. Neither principal nor keytab are not filled and JGSS credential type is initiator. * * @throws MalformedURLException */ public Krb5LoginConfiguration(final Configuration wrapped) throws MalformedURLException { this(null, null, false, wrapped); } /** * Create a new Krb5LoginConfiguration with given principal name, keytab and credential type. * * @param principal principal name, may be <code>null</code> * @param keyTab keytab file, may be <code>null</code> * @param acceptor flag for setting credential type. Set to true, if the authenticated subject should be acceptor (i.e. * credsType=acceptor for IBM JDK, and storeKey=true for Oracle JDK) * @param wrapped wrapped configuration (you can receive it for instance by calling Configuration#getConfiguration() * @throws MalformedURLException */ public Krb5LoginConfiguration(final String principal, final File keyTab, final boolean acceptor, final Configuration wrapped) throws MalformedURLException { final String loginModule = getLoginModule(); Map<String, String> options = getOptions(principal, keyTab, acceptor); configList[0] = new AppConfigurationEntry(loginModule, AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options); name = UUID.randomUUID().toString(); this.wrapped = wrapped; } /** * Returns Map with Krb5LoginModule options. The result depends on currently running JVM. * * @param principal principal name, may be <code>null</code> * @param keyTab keytab file, may be <code>null</code> * @param acceptor flag for setting credential type. Set to true, if the authenticated subject should be acceptor (i.e. * credsType=acceptor for IBM JDK, and storeKey=true for Oracle JDK) * @return HashMap with Krb5LoginModule options. */ public static Map<String, String> getOptions(final String principal, final File keyTab, final boolean acceptor) { final Map<String, String> res = new HashMap<String, String>(); if (keyTab != null) { res.put("keyTab", keyTab.getAbsolutePath()); res.put("doNotPrompt", "true"); res.put("useKeyTab", "true"); } if (acceptor) { res.put("storeKey", "true"); } res.put("refreshKrb5Config", "true"); //res.put("debug", "true"); if (principal != null) { res.put("principal", principal); } return res; } /** * Returns Krb5LoginModule class name. The returned name depends on the currently running JVM. * * @return class name */ public static String getLoginModule() { return "com.sun.security.auth.module.Krb5LoginModule"; } /** * Returns this login configuration name. * * @return */ public String getName() { return name; } /** * Returns the wrapped configuration. * * @return */ protected Configuration getWrapped() { return wrapped; } /** * Interface method requiring us to return all the LoginModules we know about. * * @param applicationName the application name * @return the configuration entry */ @Override public AppConfigurationEntry[] getAppConfigurationEntry(String applicationName) { if (name.equals(applicationName)) { // We will ignore the applicationName, since we want all apps to use Kerberos V5 return configList; } else { return wrapped == null ? null : wrapped.getAppConfigurationEntry(applicationName); } } /** * Resets configuration to the wrapped one and returns it. * * @return login configuration to which it was reseted */ public Configuration resetConfiguration() { Configuration.setConfiguration(wrapped); return wrapped; } }
5,684
34.981013
129
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/KDCServerAnnotationProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.security.common; import java.io.IOException; import java.lang.reflect.Field; import javax.security.auth.kerberos.KerberosPrincipal; import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; import org.apache.directory.server.annotations.CreateChngPwdServer; import org.apache.directory.server.annotations.CreateKdcServer; import org.apache.directory.server.annotations.CreateTransport; import org.apache.directory.server.core.annotations.AnnotationUtils; import org.apache.directory.server.core.api.DirectoryService; import org.apache.directory.server.i18n.I18n; import org.apache.directory.server.kerberos.ChangePasswordConfig; import org.apache.directory.server.kerberos.KerberosConfig; import org.apache.directory.server.kerberos.changepwd.ChangePasswordServer; import org.apache.directory.server.kerberos.kdc.KdcServer; import org.apache.directory.server.kerberos.shared.replay.ReplayCache; import org.apache.directory.server.protocol.shared.transport.TcpTransport; import org.apache.directory.server.protocol.shared.transport.Transport; import org.apache.directory.server.protocol.shared.transport.UdpTransport; import org.apache.directory.shared.kerberos.KerberosTime; import org.apache.mina.util.AvailablePortFinder; import org.jboss.logging.Logger; /** * Annotation processor for creating Kerberos servers - based on original implementation in * {@link org.apache.directory.server.factory.ServerAnnotationProcessor}. This implementation only adds a workaround for * https://issues.apache.org/jira/browse/DIRKRB-85<br/> * Use this class together with {@link ExtCreateKdcServer} annotation. * * @author Josef Cacek * @see ExtCreateKdcServer */ public class KDCServerAnnotationProcessor { // Public methods -------------------------------------------------------- /** * Creates and starts KdcServer based on configuration from {@link ExtCreateKdcServer} annotation. * * @param directoryService * @param startPort start port number used for searching free ports in case the transport has no port number preconfigured. * @return * @throws Exception */ public static KdcServer getKdcServer(DirectoryService directoryService, int startPort, String address) throws Exception { final CreateKdcServer createKdcServer = (CreateKdcServer) AnnotationUtils.getInstance(CreateKdcServer.class); return createKdcServer(createKdcServer, directoryService, startPort, address); } // Private methods ------------------------------------------------------- /** * Creates and starts {@link KdcServer} instance based on given configuration. * * @param createKdcServer * @param directoryService * @param startPort * @return */ private static KdcServer createKdcServer(CreateKdcServer createKdcServer, DirectoryService directoryService, int startPort, String bindAddress) { if (createKdcServer == null) { return null; } KerberosConfig kdcConfig = new KerberosConfig(); kdcConfig.setServicePrincipal(createKdcServer.kdcPrincipal()); kdcConfig.setPrimaryRealm(createKdcServer.primaryRealm()); kdcConfig.setMaximumTicketLifetime(createKdcServer.maxTicketLifetime()); kdcConfig.setMaximumRenewableLifetime(createKdcServer.maxRenewableLifetime()); kdcConfig.setPaEncTimestampRequired(false); KdcServer kdcServer = new NoReplayKdcServer(kdcConfig); kdcServer.setSearchBaseDn(createKdcServer.searchBaseDn()); CreateTransport[] transportBuilders = createKdcServer.transports(); if (transportBuilders == null) { // create only UDP transport if none specified UdpTransport defaultTransport = new UdpTransport(bindAddress, AvailablePortFinder.getNextAvailable(startPort)); kdcServer.addTransports(defaultTransport); } else if (transportBuilders.length > 0) { for (CreateTransport transportBuilder : transportBuilders) { String protocol = transportBuilder.protocol(); int port = transportBuilder.port(); int nbThreads = transportBuilder.nbThreads(); int backlog = transportBuilder.backlog(); final String address = bindAddress != null ? bindAddress : transportBuilder.address(); if (port == -1) { port = AvailablePortFinder.getNextAvailable(startPort); startPort = port + 1; } if (protocol.equalsIgnoreCase("TCP")) { Transport tcp = new TcpTransport(address, port, nbThreads, backlog); kdcServer.addTransports(tcp); } else if (protocol.equalsIgnoreCase("UDP")) { UdpTransport udp = new UdpTransport(address, port); kdcServer.addTransports(udp); } else { throw new IllegalArgumentException(I18n.err(I18n.ERR_689, protocol)); } } } CreateChngPwdServer[] createChngPwdServers = createKdcServer.chngPwdServer(); if (createChngPwdServers.length > 0) { CreateChngPwdServer createChngPwdServer = createChngPwdServers[0]; ChangePasswordConfig config = new ChangePasswordConfig(kdcConfig); config.setServicePrincipal(createChngPwdServer.srvPrincipal()); ChangePasswordServer chngPwdServer = new ChangePasswordServer(config); for (CreateTransport transportBuilder : createChngPwdServer.transports()) { Transport t = createTransport(transportBuilder, startPort); startPort = t.getPort() + 1; chngPwdServer.addTransports(t); } chngPwdServer.setDirectoryService(directoryService); kdcServer.setChangePwdServer(chngPwdServer); } kdcServer.setDirectoryService(directoryService); // Launch the server try { kdcServer.start(); } catch (Exception e) { e.printStackTrace(); } return kdcServer; } private static Transport createTransport( CreateTransport transportBuilder, int startPort ) { String protocol = transportBuilder.protocol(); int port = transportBuilder.port(); int nbThreads = transportBuilder.nbThreads(); int backlog = transportBuilder.backlog(); String address = transportBuilder.address(); if ( port == -1 ) { port = AvailablePortFinder.getNextAvailable( startPort ); startPort = port + 1; } if ( protocol.equalsIgnoreCase( "TCP" ) ) { Transport tcp = new TcpTransport( address, port, nbThreads, backlog ); return tcp; } else if ( protocol.equalsIgnoreCase( "UDP" ) ) { UdpTransport udp = new UdpTransport( address, port ); return udp; } else { throw new IllegalArgumentException( I18n.err( I18n.ERR_689, protocol ) ); } } } /** * * Replacement of apacheDS KdcServer class with disabled ticket replay cache. * * @author Dominik Pospisil <dpospisi@redhat.com> */ class NoReplayKdcServer extends KdcServer { NoReplayKdcServer(KerberosConfig kdcConfig) { super(kdcConfig); } private static Logger LOGGER = Logger.getLogger(NoReplayKdcServer.class); /** * * Dummy implementation of the ApacheDS kerberos replay cache. Essentially disables kerbores ticket replay checks. * https://issues.jboss.org/browse/JBPAPP-10974 * * @author Dominik Pospisil <dpospisi@redhat.com> */ private class DummyReplayCache implements ReplayCache { @Override public boolean isReplay(KerberosPrincipal serverPrincipal, KerberosPrincipal clientPrincipal, KerberosTime clientTime, int clientMicroSeconds) { return false; } @Override public void save(KerberosPrincipal serverPrincipal, KerberosPrincipal clientPrincipal, KerberosTime clientTime, int clientMicroSeconds) { return; } @Override public void clear() { return; } } /** * @throws IOException if we cannot bind to the sockets */ public void start() throws IOException, LdapInvalidDnException { super.start(); try { // override initialized replay cache with a dummy implementation Field replayCacheField = KdcServer.class.getDeclaredField("replayCache"); replayCacheField.setAccessible(true); replayCacheField.set(this, new DummyReplayCache()); } catch (Exception e) { LOGGER.warn("Unable to override replay cache.", e); } } }
9,968
38.094118
127
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/RolesPrintingServletUtils.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.security.common; import static org.junit.Assert.fail; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import org.jboss.as.test.integration.security.common.servlets.RolePrintingServlet; /** * Utils class for related methods to printing roles by * {@code org.jboss.as.test.integration.security.common.servlets.RolePrintingServlet}. * * @author olukas */ public class RolesPrintingServletUtils { /** * Prepare URL for printing all possible roles. * * @param webAppURL application root URL * @param allPossibleRoles all possible roles which will be checked by {@link RolePrintingServlets} * @return */ public static URL prepareRolePrintingUrl(URL webAppURL, String[] allPossibleRoles) { final List<NameValuePair> qparams = new ArrayList<>(); for (final String role : allPossibleRoles) { qparams.add(new BasicNameValuePair(RolePrintingServlet.PARAM_ROLE_NAME, role)); } String queryRoles = URLEncodedUtils.format(qparams, StandardCharsets.UTF_8); try { return new URL(webAppURL.toExternalForm() + RolePrintingServlet.SERVLET_PATH.substring(1) + "?" + queryRoles); } catch (MalformedURLException ex) { throw new RuntimeException(ex); } } /** * Check whether Response includes only expected roles. It checks whether all expected roles are included and whether no * other role is included. * * @param rolesResponse body of HTTP response * @param allPossibleRoles all possible roles which can be assigned * @param expectedAssignedRoles roles which will be checked whether they were assigned to user */ public static void assertExpectedRoles(String rolesResponse, String[] allPossibleRoles, String[] expectedAssignedRoles) { final List<String> assignedRolesList = Arrays.asList(expectedAssignedRoles); // for checking whether all roles which should be checked are really checked int checkedRoles = 0; for (String role : allPossibleRoles) { if (assignedRolesList.contains(role)) { assertInRole(rolesResponse, role); checkedRoles++; } else { assertNotInRole(rolesResponse, role); } } if (assignedRolesList.size() != checkedRoles) { throw new RuntimeException("There are some roles which have not been checked. It is probably test case issue - " + "you try to check some roles which are missing in all possible roles array."); } } /** * Asserts, the role list returned from the {@link RolePrintingServlet} contains the given role. * * @param rolePrintResponse * @param role */ private static void assertInRole(final String rolePrintResponse, String role) { if (!StringUtils.contains(rolePrintResponse, "," + role + ",")) { fail("Missing role '" + role + "' assignment"); } } /** * Asserts, the role list returned from the {@link RolePrintingServlet} doesn't contain the given role. * * @param rolePrintResponse * @param role */ private static void assertNotInRole(final String rolePrintResponse, String role) { if (StringUtils.contains(rolePrintResponse, "," + role + ",")) { fail("Unexpected role '" + role + "' assignment"); } } }
4,796
39.310924
125
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/servlets/PrincipalPrintingServlet.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.security.common.servlets; import java.io.IOException; import java.io.PrintWriter; import java.security.Principal; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * A servlet which reports the name of the callers principal. * * @author JanLanik */ @WebServlet(name = "PrincipalPrintingServlet", urlPatterns = { PrincipalPrintingServlet.SERVLET_PATH }) public class PrincipalPrintingServlet extends HttpServlet { private static final long serialVersionUID = 1L; public static final String SERVLET_PATH = "/printPrincipal"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); final PrintWriter writer = resp.getWriter(); final Principal principal = req.getUserPrincipal(); if (null == principal) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Principal name is printed only for the authenticated users."); } else { writer.write(principal.getName()); } writer.close(); } }
2,333
38.559322
124
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/servlets/RolePrintingServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.security.common.servlets; import java.io.IOException; import java.io.PrintWriter; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.HttpConstraint; import jakarta.servlet.annotation.ServletSecurity; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * A RolePrintingServlet gets list of role names as (GET) request parameters and returns a comma separated sublist of such role * names for which {@link HttpServletRequest#isUserInRole(String)} returns <code>true</code>. Don't forget to declare the tested * roles in the web.xml file. * * @author Josef Cacek */ @WebServlet(urlPatterns = { RolePrintingServlet.SERVLET_PATH }) @ServletSecurity(@HttpConstraint(rolesAllowed = { "*" })) public class RolePrintingServlet extends HttpServlet { /** The serialVersionUID */ private static final long serialVersionUID = 1L; /** Name of the HTTP request parameter which holds a role name. */ public static String PARAM_ROLE_NAME = "role"; /** The default servlet path (used in {@link WebServlet} annotation). */ public static final String SERVLET_PATH = "/printRoles"; // Protected methods ----------------------------------------------------- /** * Writes plain-text response with the comma-separated role names (subset of the names retrieved as GET parameters). * * @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(); final String[] roleNames = req.getParameterValues(PARAM_ROLE_NAME); //start with the comma to simplify exact search (e.g. for role 'admin' an user can search for ',admin,') writer.write(","); if (roleNames != null) { for (final String role : roleNames) { if (req.isUserInRole(role)) { writer.write(role + ","); } } } writer.close(); } }
3,461
41.219512
133
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/servlets/SimpleSecuredServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.security.common.servlets; import jakarta.annotation.security.DeclareRoles; import jakarta.servlet.annotation.HttpConstraint; import jakarta.servlet.annotation.ServletSecurity; import jakarta.servlet.annotation.WebServlet; /** * Protected version of {@link SimpleServlet}. Only {@value #ALLOWED_ROLE} role has access right. * * @author Josef Cacek */ @DeclareRoles({ SimpleSecuredServlet.ALLOWED_ROLE }) @ServletSecurity(@HttpConstraint(rolesAllowed = { SimpleSecuredServlet.ALLOWED_ROLE })) @WebServlet(SimpleSecuredServlet.SERVLET_PATH) public class SimpleSecuredServlet extends SimpleServlet { /** The serialVersionUID */ private static final long serialVersionUID = 1L; public static final String SERVLET_PATH = "/SimpleSecuredServlet"; public static final String ALLOWED_ROLE = "JBossAdmin"; }
1,882
41.795455
97
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/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.test.integration.security.common.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,492
39.868852
126
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/servlets/SimpleServlet.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.security.common.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; /** * A simple servlet that just writes back a string. * * @author Josef Cacek */ @WebServlet(urlPatterns = { SimpleServlet.SERVLET_PATH }) public class SimpleServlet extends HttpServlet { private static final long serialVersionUID = 1L; public static final String SERVLET_PATH = "/unsecured"; /** The String returned in the HTTP response body. */ public static final String RESPONSE_BODY = "GOOD"; /** Name of a request parameter (parsed as a boolean), which says if a session should be created. */ public static final String CREATE_SESSION_PARAM = "createSession"; /** * Writes simple text response. * * @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(); if (Boolean.parseBoolean(req.getParameter(CREATE_SESSION_PARAM))) { req.getSession(); } writer.write(RESPONSE_BODY); writer.close(); } }
2,673
36.661972
133
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/servlets/PrintAttributeServlet.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.security.common.servlets; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import org.jboss.logging.Logger; /** * This servlet prints value of an request/session attribute. It supports also nested values for {@link Map} and {@link List} * instances - names in such case are delimited by {@value #DELIMITER}. * <p> * The servlet supports 2 parameters: * <ul> * <li>{@value #PARAM_ATTR_NAME} - name of attribute to retrieve. Default value is {@value #DEFAULT_PROPERTY_NAME}</li> * <li>{@value #PARAM_SCOPE_NAME} - scope from which the value should be retrieved. Supported vaules are "session" and * "request". Default is {@value #DEFAULT_SCOPE_NAME}</li> * </ul> * <p> * For instance the Picketlink's handler SAML2AttributeHandler stores a map with attributes received in SAML assertion to an * {@link HttpSession} as attribute named "SESSION_ATTRIBUTE_MAP". Each entry in this map is represented by a list of values. So * if you want to read the first value of SAML assertion attribute named "cn" from the session, use the parameter * "attrib=SESSION_ATTRIBUTE_MAP/cn/0" * * @author Josef Cacek */ @WebServlet(PrintAttributeServlet.SERVLET_PATH) public class PrintAttributeServlet extends HttpServlet { private static Logger LOGGER = Logger.getLogger(PrintAttributeServlet.class); private static final long serialVersionUID = 1L; public static final String SERVLET_PATH = "/PrintAttrServlet"; public static final String PARAM_ATTR_NAME = "attr"; public static final String PARAM_SCOPE_NAME = "scope"; public static final String DELIMITER = "/"; public static final String DEFAULT_PROPERTY_NAME = "SESSION_ATTRIBUTE_MAP" + DELIMITER + "cn" + DELIMITER + "0"; public static final String SCOPE_REQUEST = "request"; public static final String SCOPE_SESSION = "session"; public static final String DEFAULT_SCOPE_NAME = SCOPE_SESSION; @SuppressWarnings("rawtypes") @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); String attrName = req.getParameter(PARAM_ATTR_NAME); if (attrName == null || attrName.length() == 0) { attrName = DEFAULT_PROPERTY_NAME; } StringTokenizer st = new StringTokenizer(attrName, DELIMITER); String actualName = st.nextToken(); Object actualValue = null; if (SCOPE_REQUEST.equalsIgnoreCase(req.getParameter(PARAM_SCOPE_NAME))) { actualValue = req.getAttribute(actualName); } else { final HttpSession session = req.getSession(false); if (session != null) actualValue = session.getAttribute(actualName); } while (st.hasMoreTokens() && (actualValue instanceof Map || actualValue instanceof List)) { actualName = st.nextToken(); if (actualValue instanceof List) { try { actualValue = ((List) actualValue).get(Integer.parseInt(actualName)); } catch (Exception e) { LOGGER.warn("Unable to retrieve value from list", e); actualValue = null; } } else { actualValue = ((Map) actualValue).get(actualName); } } final PrintWriter writer = resp.getWriter(); writer.write(String.valueOf(actualValue)); writer.close(); } }
4,884
42.616071
128
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/servlets/DataSourceTestServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.security.common.servlets; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; 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 makes a simple test on the given datasource ("ExampleDS" by default, use {@value #PARAM_DS} request parameter * to change the tested datasource). This servlet lookups the datasource through JNDI and follows these steps: * <ol> * <li>get Connection from DS</li> * <li>create Statement</li> * <li>create table</li> * <li>insert record</li> * <li>run query and check if the inserted record is returned</li> * <li>drop table</li> * <li>close resources</li> * <ol> * * If everything finishes as expected then "true" is returned as the response body. If query doesn't return expected value then * the response body is "false".<br> * The response contains stack trace in case of SQLException or NamingException.<br> * The response content type is text/plain. * * @author Josef Cacek */ @WebServlet(DataSourceTestServlet.SERVLET_PATH) public class DataSourceTestServlet extends HttpServlet { private static final long serialVersionUID = 1L; public static final String SERVLET_PATH = "/DataSourceTestServlet"; public static final String PARAM_DS = "datasource"; public static final String PARAM_DS_DEFAULT = "ExampleDS"; @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); String datasourceName = req.getParameter(PARAM_DS); if (datasourceName == null || datasourceName.length() == 0) { datasourceName = PARAM_DS_DEFAULT; } final PrintWriter writer = resp.getWriter(); Connection con = null; try { InitialContext iniCtx = new InitialContext(); DataSource ds = (DataSource) iniCtx.lookup("java:jboss/datasources/" + datasourceName); con = ds.getConnection(); Statement stmt = con.createStatement(); stmt.executeUpdate("create table testtable(testid int)"); stmt.executeUpdate("insert into testtable values (1)"); ResultSet rs = stmt.executeQuery("select * from testtable"); writer.print(rs.next() && 1 == rs.getInt(1)); rs.close(); stmt.executeUpdate("drop table testtable"); stmt.close(); } catch (SQLException e) { e.printStackTrace(writer); } catch (NamingException e) { e.printStackTrace(writer); } finally { if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
4,227
37.436364
127
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/ejb3/HelloBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.security.common.ejb3; import jakarta.annotation.Resource; import jakarta.annotation.security.DeclareRoles; import jakarta.annotation.security.RolesAllowed; import jakarta.ejb.Remote; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateless; /** * A simple implementation of {@link Hello} interface. It's annotated as a {@link Stateless} bean with {@link Hello} as a * {@link Remote remote} interface. Access to the methods is protected and only {@value #ROLE_ALLOWED} role has access. * * @author Josef Cacek */ @DeclareRoles(HelloBean.ROLE_ALLOWED) @Stateless @RolesAllowed(HelloBean.ROLE_ALLOWED) @Remote(Hello.class) public class HelloBean implements Hello { public static final String ROLE_ALLOWED = "TestRole"; public static final String HELLO_WORLD = "Hello world!"; @Resource private SessionContext context; // Public methods -------------------------------------------------------- /** * Returns {@value #HELLO_WORLD}. * * @see Hello#sayHelloWorld() */ public String sayHelloWorld() { return HELLO_WORLD; } /** * Returns greeting with name retrieved from {@link SessionContext#getCallerPrincipal()}. * * @see Hello#sayHello() */ public String sayHello() { return "Hello " + context.getCallerPrincipal().getName() + "!"; } }
2,414
33.014085
121
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/ejb3/Hello.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.security.common.ejb3; /** * An interface for basic Jakarta Enterprise Beans tests. * * @author Josef Cacek */ public interface Hello { /** * Returns a greeting. * * @return */ String sayHelloWorld(); /** * Returns returns greeting with caller principal name. * * @return */ String sayHello(); }
1,420
29.891304
70
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/common/DefaultConfiguration.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.common; import java.util.HashMap; import java.util.Properties; import javax.management.remote.JMXConnector; import javax.naming.Context; import org.jboss.as.test.http.Authentication; import org.jboss.as.test.shared.integration.ejb.security.CallbackHandler; /** * Created by fspolti on 10/20/16. * WFLY-7309 / JBEAP-6424 */ public class DefaultConfiguration { private static final boolean isRemote = Boolean.parseBoolean(System.getProperty("org.jboss.as.test.integration.remote", "false")); private static final String MBEAN_USERNAME = System.getProperty("jboss.mbean.username", Authentication.USERNAME); private static final String MBEAN_PASSWORD = System.getProperty("jboss.mbean.username", Authentication.PASSWORD); private static final String APPLICATION_USERNAME = System.getProperty("jboss.application.username", "guest"); private static final String APPLICATION_PASSWORD = System.getProperty("jboss.application.username", "guest"); /* * Return the value of isRemote variable, it will be used to define * if the tests are abring running in a local or remote container. If no value * is provided then the default value is false (local) */ public static boolean isRemote() { return isRemote; } /* * Return the application username, if none is provided it will return the default: * guest */ public static String applicationUsername() { return APPLICATION_USERNAME; } /* * Return the application password, if none is provided it will return the default: * guest */ public static String applicationPassword() { return APPLICATION_PASSWORD; } /* * Returns a HashMap containing the credentials for a JMX connection * default user and pass is testSuite/testSuitePassword */ public static HashMap<String, String[]> credentials () { HashMap<String, String[]> propEnv = new HashMap<String, String[]>(); String[] credentials = { MBEAN_USERNAME, MBEAN_PASSWORD }; propEnv.put(JMXConnector.CREDENTIALS, credentials); return isRemote() ? propEnv : null; } /* * Returns the env Properties updated with security configurations for Jakarta Enterprise Beans connections * @param env the properties to be updated * @return the Properties updated */ public static Properties addSecurityProperties(Properties env) { if (isRemote()){ env.put(Context.SECURITY_PRINCIPAL, applicationUsername()); env.put(Context.SECURITY_CREDENTIALS, applicationPassword()); } else { env.put("jboss.naming.client.security.callback.handler.class", CallbackHandler.class.getName()); } return env; } }
3,809
39.105263
134
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/common/Naming.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.common; import javax.naming.InitialContext; import javax.naming.NamingException; /** * @author <a href="mailto:cdewolf@redhat.com">Carlo de Wolf</a> */ public class Naming { 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(); } } }
1,519
36.073171
94
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/common/WebInfLibClass.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.common; public class WebInfLibClass { }
1,096
39.62963
73
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/common/JndiServlet.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.common; import java.io.IOException; import java.io.PrintWriter; import java.net.URLEncoder; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.naming.InitialContext; import javax.naming.NameNotFoundException; 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; /** * Servlet which does JNDI lookup and returns looked up object class name in Http response. Lookup name is specified through * request parameter "name". * * @author Dominik Pospisil <dpospisi@redhat.com> */ @WebServlet(urlPatterns = {"/JndiServlet"}) public class JndiServlet extends HttpServlet { public static final String NOT_FOUND = "NOT_FOUND"; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, NamingException { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); String name = request.getParameter("name"); if (name == null) { throw new ServletException("Lookup name not specified."); } InitialContext ctx = new InitialContext(); Object obj = null; try { obj = ctx.lookup(name); out.print(obj.getClass().getName()); } catch (NameNotFoundException nnfe) { out.print(NOT_FOUND); } out.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (NamingException ne) { throw new ServletException(ne); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (NamingException ne) { throw new ServletException(ne); } } /* * Simple servlet's client. */ public static String lookup(String URL, String name) throws IOException { try { return HttpRequest.get(URL + "/JndiServlet?name=" + URLEncoder.encode(name, "UTF-8"), 5, TimeUnit.SECONDS); } catch (ExecutionException ex) { return null; } catch (TimeoutException ex) { return null; } } }
3,707
35
124
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/common/jms/ArtemisRunListener.java
/* * Copyright 2020 Emmanuel Hugonnet (c) 2020 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.common.jms; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.core.settings.impl.AddressFullMessagePolicy; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.utils.FileUtil; import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.RunListener; /** * * @author Emmanuel Hugonnet (c) 2020 Red Hat, Inc. */ public class ArtemisRunListener extends RunListener { private ActiveMQServer server; // Using files may be useful for debugging (through print-data for instance) private static final boolean PERSISTENCE = false; public static void main(final String[] args) throws Exception { ArtemisRunListener listener = new ArtemisRunListener(); try { listener.startServer(); System.out.println("Server started, ready to start client test"); // create the reader before printing OK so that if the test is quick // we will still capture the STOP message sent by the client InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); System.out.println("OK"); String line = br.readLine(); if (line != null && "STOP".equals(line.trim())) { listener.stopServer(); System.out.println("Server stopped"); System.exit(0); } else { // stop anyway but with an error status System.exit(1); } } catch (Throwable t) { t.printStackTrace(); String allStack = t.getCause().getMessage() + "|"; StackTraceElement[] stackTrace = t.getCause().getStackTrace(); for (StackTraceElement stackTraceElement : stackTrace) { allStack += stackTraceElement.toString() + "|"; } System.out.println(allStack); System.out.println("KO"); System.exit(1); } } private synchronized ActiveMQServer startServer() throws Exception { if (server == null) { Configuration config = new ConfigurationImpl() .setName("Test-Broker") .addAcceptorConfiguration("netty", getBrokerUrl()) .setSecurityEnabled(false) .setPersistenceEnabled(false) .setJournalFileSize(10 * 1024 * 1024) .setJournalDeviceBlockSize(4096) .setJournalMinFiles(2) .setJournalDatasync(true) .setJournalPoolFiles(10) .addConnectorConfiguration("netty", getBrokerUrl()); File dataPlace = new File(getArtemisHome()); FileUtil.deleteDirectory(dataPlace); config.setJournalDirectory(new File(dataPlace, "./journal").getAbsolutePath()). setPagingDirectory(new File(dataPlace, "./paging").getAbsolutePath()). setLargeMessagesDirectory(new File(dataPlace, "./largemessages").getAbsolutePath()). setBindingsDirectory(new File(dataPlace, "./bindings").getAbsolutePath()).setPersistenceEnabled(true); server = ActiveMQServers.newActiveMQServer(config, PERSISTENCE); server.getAddressSettingsRepository().addMatch("#", new AddressSettings() .setDeadLetterAddress(SimpleString.toSimpleString("DLQ")) .setExpiryAddress(SimpleString.toSimpleString("ExpiryQueue")) .setRedeliveryDelay(0) .setMaxSizeBytes(-1) .setMessageCounterHistoryDayLimit(10) .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE) .setAutoCreateQueues(true) .setAutoCreateAddresses(true) .setAutoCreateJmsQueues(true) .setAutoCreateJmsTopics(true)); server.getAddressSettingsRepository().addMatch("activemq.management#", new AddressSettings() .setDeadLetterAddress(SimpleString.toSimpleString("DLQ")) .setExpiryAddress(SimpleString.toSimpleString("ExpiryQueue")) .setRedeliveryDelay(0) .setMaxSizeBytes(-1) .setMessageCounterHistoryDayLimit(10) .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE) .setAutoCreateQueues(true) .setAutoCreateAddresses(true) .setAutoCreateJmsQueues(true) .setAutoCreateJmsTopics(true)); server.start(); server.waitForActivation(10, TimeUnit.SECONDS); } return server; } @Override public void testRunFinished(Result result) throws Exception { stopServer(); super.testRunFinished(result); } @Override public void testRunStarted(Description description) throws Exception { startServer(); super.testRunStarted(description); } @Override public void testStarted(Description description) throws Exception { super.testStarted(description); } private String getArtemisHome() { String artemisHome = System.getProperty("artemis.dist"); if (artemisHome == null) { artemisHome = System.getProperty("artemis.home"); } return artemisHome == null ? System.getenv("ARTEMIS_HOME") : artemisHome; } private synchronized void stopServer() throws Exception { if (server != null) { server.stop(); } server = null; } private String getBrokerUrl() { return "tcp://" + getServerAddress() + ":" + getServerPort(); } private String getServerAddress() { String address = System.getProperty("management.address"); if (address == null) { address = System.getProperty("node0"); } if (address != null) { return formatPossibleIpv6Address(address); } return "localhost"; } private String formatPossibleIpv6Address(String address) { if (address == null) { return address; } if (!address.contains(":")) { return address; } if (address.startsWith("[") && address.endsWith("]")) { return address; } return "[" + address + "]"; } private int getServerPort() { //this here is just fallback logic for older testsuite code that wasn't updated to newer property names return Integer.getInteger("artemis.port", 61616); } }
7,819
38.695431
122
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/common/jms/JMSOperationsProvider.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.common.jms; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.ClientConstants; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; /** * Utility class for getting implementations of JMSOperations interface * @author <a href="jmartisk@redhat.com">Jan Martiska</a> */ public class JMSOperationsProvider { private static final Logger logger = Logger.getLogger(JMSOperationsProvider.class); private static final String PROPERTY_NAME = "jmsoperations.implementation.class"; private static final String FILE_NAME = "jmsoperations.properties"; /** * Gets an instance of a JMSOperations implementation for a particular Jakarta Messaging provider based on the classname * given by property "jmsoperations.implementation.class" in jmsoperations.properties somewhere on the classpath * The property should contain a fully qualified name of a class that implements JMSOperations interface * The setting in that file can be overriden by a system property declaration * * @param client {@link ManagementClient} to pass to the JMSOperations implementation class' constructor * * @return a JMSOperations implementation that is JMS-provider-dependent * * @deprecated use {@link #getInstance(ModelControllerClient)} instead */ @Deprecated public static JMSOperations getInstance(ManagementClient client) { String className; // first try to get the property from system properties className = System.getProperty(PROPERTY_NAME); // if this was not defined, try to get it from jmsoperations.properties if(className == null) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); InputStream stream = tccl.getResourceAsStream(FILE_NAME); Properties propsFromFile = new Properties(); try { propsFromFile.load(stream); className = propsFromFile.getProperty(PROPERTY_NAME); } catch(IOException ex) { throw new RuntimeException(ex); } } if(className == null) { throw new JMSOperationsException("Please specify a property " + PROPERTY_NAME + " in " + FILE_NAME); } Object jmsOperationsInstance; try { Class clazz = Class.forName(className); jmsOperationsInstance = clazz.getConstructor(ManagementClient.class).newInstance(client); } catch (Exception e) { throw new JMSOperationsException(e); } if(!(jmsOperationsInstance instanceof JMSOperations)) { throw new JMSOperationsException("Class " + className + " does not implement interface JMSOperations"); } return (JMSOperations)jmsOperationsInstance; } /** * Gets an instance of a JMSOperations implementation for a particular Jakarta Messaging provider based on the classname * given by property "jmsoperations.implementation.class" in jmsoperations.properties somewhere on the classpath * The property should contain a fully qualified name of a class that implements JMSOperations interface * The setting in that file can be overriden by a system property declaration * * @param client {@link ModelControllerClient} to pass to the JMSOperations implementation class' constructor * * @return a JMSOperations implementation that is JMS-provider-dependent */ public static JMSOperations getInstance(ModelControllerClient client) { String className; // first try to get the property from system properties className = System.getProperty(PROPERTY_NAME); // if this was not defined, try to get it from jmsoperations.properties if (className == null) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); InputStream stream = tccl.getResourceAsStream(FILE_NAME); Properties propsFromFile = new Properties(); try { propsFromFile.load(stream); className = propsFromFile.getProperty(PROPERTY_NAME); } catch(IOException ex) { throw new RuntimeException(ex); } } if(className == null) { throw new JMSOperationsException("Please specify a property " + PROPERTY_NAME + " in " + FILE_NAME); } Object jmsOperationsInstance; try { Class clazz = Class.forName(className); jmsOperationsInstance = clazz.getConstructor(ModelControllerClient.class).newInstance(client); } catch (Exception e) { throw new JMSOperationsException(e); } if (!(jmsOperationsInstance instanceof JMSOperations)) { throw new JMSOperationsException("Class " + className + " does not implement interface JMSOperations"); } return (JMSOperations)jmsOperationsInstance; } static void execute(ManagementClient managementClient, final ModelNode operation) throws IOException, JMSOperationsException { execute(managementClient.getControllerClient(), operation); } static void execute(ModelControllerClient client, final ModelNode operation) throws IOException, JMSOperationsException { ModelNode result = client.execute(operation); if (result.hasDefined(ClientConstants.OUTCOME) && ClientConstants.SUCCESS.equals(result.get(ClientConstants.OUTCOME).asString())) { logger.trace("Operation successful for update = " + operation.toString()); } else if (result.hasDefined(ClientConstants.FAILURE_DESCRIPTION)) { final String failureDesc = result.get(ClientConstants.FAILURE_DESCRIPTION).toString(); throw new JMSOperationsException(failureDesc); } else { throw new JMSOperationsException("Operation not successful; outcome = " + result.get(ClientConstants.OUTCOME)); } } }
7,215
47.106667
139
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/common/jms/ActiveMQProviderJMSOperations.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.common.jms; import static org.jboss.as.controller.client.helpers.ClientConstants.ADD; import static org.jboss.as.controller.client.helpers.ClientConstants.REMOVE_OPERATION; 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.integration.common.jms.JMSOperationsProvider.execute; import java.util.Map; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; /** * An implementation of JMSOperations for Apache ActiveMQ 6. * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc. */ public class ActiveMQProviderJMSOperations implements JMSOperations { private final ModelControllerClient client; public ActiveMQProviderJMSOperations(ModelControllerClient client) { this.client = client; } public ActiveMQProviderJMSOperations(ManagementClient client) { this.client = client.getControllerClient(); } private static final ModelNode subsystemAddress = new ModelNode(); static { subsystemAddress.add("subsystem", "messaging-activemq"); } private static final ModelNode serverAddress = new ModelNode(); static { serverAddress.add("subsystem", "messaging-activemq"); serverAddress.add("server", "default"); } @Override public ModelControllerClient getControllerClient() { return client; } @Override public ModelNode getServerAddress() { return serverAddress.clone(); } @Override public ModelNode getSubsystemAddress() { return subsystemAddress.clone(); } @Override public String getProviderName() { return "activemq"; } @Override public void createJmsQueue(String queueName, String jndiName) { createJmsQueue(queueName, jndiName, new ModelNode()); } @Override public void createJmsQueue(String queueName, String jndiName, ModelNode attributes) { ModelNode address = getServerAddress() .add("jms-queue", queueName); attributes.get("entries").add(jndiName); executeOperation(address, ADD, attributes); } @Override public void createJmsTopic(String topicName, String jndiName) { createJmsTopic(topicName, jndiName, new ModelNode()); } @Override public void createJmsTopic(String topicName, String jndiName, ModelNode attributes) { ModelNode address = getServerAddress() .add("jms-topic", topicName); attributes.get("entries").add(jndiName); executeOperation(address, ADD, attributes); } @Override public void removeJmsQueue(String queueName) { ModelNode address = getServerAddress() .add("jms-queue", queueName); executeOperation(address, REMOVE_OPERATION, null); } @Override public void removeJmsTopic(String topicName) { ModelNode address = getServerAddress() .add("jms-topic", topicName); executeOperation(address, REMOVE_OPERATION, null); } @Override public void addJmsConnectionFactory(String name, String jndiName, ModelNode attributes) { ModelNode address = getServerAddress() .add("connection-factory", name); attributes.get("entries").add(jndiName); executeOperation(address, ADD, attributes); } @Override public void removeJmsConnectionFactory(String name) { ModelNode address = getServerAddress() .add("connection-factory", name); executeOperation(address, REMOVE_OPERATION, null); } @Override public void addJmsExternalConnectionFactory(String name, String jndiName, ModelNode attributes) { ModelNode address = getSubsystemAddress() .add("connection-factory", name); attributes.get("entries").add(jndiName); executeOperation(address, ADD, attributes); } @Override public void removeJmsExternalConnectionFactory(String name) { ModelNode address = getSubsystemAddress() .add("connection-factory", name); executeOperation(address, REMOVE_OPERATION, null); } @Override public void addJmsBridge(String name, ModelNode attributes) { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("jms-bridge", name); executeOperation(address, ADD, attributes); } @Override public void removeJmsBridge(String name) { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("jms-bridge", name); executeOperation(address, REMOVE_OPERATION, null); } @Override public void addCoreBridge(String name, ModelNode attributes) { ModelNode address = getServerAddress(); address.add("bridge", name); executeOperation(address, ADD, attributes); } @Override public void removeCoreBridge(String name) { ModelNode address = getServerAddress(); address.add("bridge", name); executeOperation(address, REMOVE_OPERATION, null); } @Override public void addCoreQueue(String queueName, String queueAddress, boolean durable, String routing) { ModelNode address = getServerAddress() .add("queue", queueName); ModelNode attributes = new ModelNode(); attributes.get("queue-address").set(queueAddress); attributes.get("durable").set(durable); attributes.get("routing-type").set(routing); executeOperation(address, ADD, attributes); } @Override public void removeCoreQueue(String queueName) { ModelNode address = getServerAddress() .add("queue", queueName); executeOperation(address, REMOVE_OPERATION, null); } @Override public void createRemoteAcceptor(String name, String socketBinding, Map<String, String> params) { ModelNode model = getServerAddress().add("remote-acceptor", name); ModelNode attributes = new ModelNode(); attributes.get("socket-binding").set(socketBinding); if (params != null) { addParams(params, model); } executeOperation(model, ADD, attributes); } private void addParams(Map<String, String> params, ModelNode model) { for (Map.Entry<String, String> entry : params.entrySet()) { model.get("params").add(entry.getKey(), entry.getValue()); } } @Override public void removeRemoteAcceptor(String name) { ModelNode model = getServerAddress().add("remote-acceptor", name); executeOperation(model, REMOVE_OPERATION, null); } @Override public void close() { // no-op // DO NOT close the management client. Whoever passed it into the constructor should close it } private void executeOperation(final ModelNode address, final String opName, ModelNode attributes) { final ModelNode operation = new ModelNode(); operation.get(OP).set(opName); operation.get(OP_ADDR).set(address); if (attributes != null) { for (Property property : attributes.asPropertyList()) { operation.get(property.getName()).set(property.getValue()); } } try { execute(client, operation); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void setSystemProperties(String destination, String resourceAdapter) { final ModelNode enableSubstitutionOp = new ModelNode(); enableSubstitutionOp.get(OP_ADDR).set(SUBSYSTEM, "ee"); enableSubstitutionOp.get(OP).set(WRITE_ATTRIBUTE_OPERATION); enableSubstitutionOp.get(NAME).set("annotation-property-replacement"); enableSubstitutionOp.get(VALUE).set(true); final ModelNode setDestinationOp = new ModelNode(); setDestinationOp.get(OP).set(ADD); setDestinationOp.get(OP_ADDR).add("system-property", "destination"); setDestinationOp.get("value").set(destination); final ModelNode setResourceAdapterOp = new ModelNode(); setResourceAdapterOp.get(OP).set(ADD); setResourceAdapterOp.get(OP_ADDR).add("system-property", "resource.adapter"); setResourceAdapterOp.get("value").set(resourceAdapter); try { execute(client, enableSubstitutionOp); execute(client, setDestinationOp); execute(client, setResourceAdapterOp); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void removeSystemProperties() { final ModelNode removeDestinationOp = new ModelNode(); removeDestinationOp.get(OP).set("remove"); removeDestinationOp.get(OP_ADDR).add("system-property", "destination"); final ModelNode removeResourceAdapterOp = new ModelNode(); removeResourceAdapterOp.get(OP).set("remove"); removeResourceAdapterOp.get(OP_ADDR).add("system-property", "resource.adapter"); final ModelNode disableSubstitutionOp = new ModelNode(); disableSubstitutionOp.get(OP_ADDR).set(SUBSYSTEM, "ee"); disableSubstitutionOp.get(OP).set(WRITE_ATTRIBUTE_OPERATION); disableSubstitutionOp.get(NAME).set("annotation-property-replacement"); disableSubstitutionOp.get(VALUE).set(false); try { execute(client, removeDestinationOp); execute(client, removeResourceAdapterOp); execute(client, disableSubstitutionOp); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void addHttpConnector(String connectorName, String socketBinding, String endpoint, Map<String, String> parameters) { ModelNode address = getServerAddress().add("http-connector", connectorName); ModelNode attributes = new ModelNode(); attributes.get("socket-binding").set(socketBinding); attributes.get("endpoint").set(endpoint); if (parameters != null && parameters.size() > 0) { ModelNode params = attributes.get("params").setEmptyList(); for (Map.Entry<String, String> param : parameters.entrySet()) { params.add(param.getKey(), param.getValue()); } } executeOperation(address, ADD, attributes); } @Override public void removeHttpConnector(String connectorName) { ModelNode address = getServerAddress() .add("http-connector", connectorName); executeOperation(address, REMOVE_OPERATION, null); } @Override public void addExternalHttpConnector(String connectorName, String socketBinding, String endpoint) { ModelNode address = getSubsystemAddress() .add("http-connector", connectorName); ModelNode attributes = new ModelNode(); attributes.get("socket-binding").set(socketBinding); attributes.get("endpoint").set(endpoint); executeOperation(address, ADD, attributes); } @Override public void addExternalRemoteConnector(String name, String socketBinding) { ModelNode address = getSubsystemAddress() .add("remote-connector", name); ModelNode attributes = new ModelNode(); attributes.get("socket-binding").set(socketBinding); executeOperation(address, ADD, attributes); } @Override public void removeExternalHttpConnector(String connectorName) { ModelNode address = getSubsystemAddress() .add("http-connector", connectorName); executeOperation(address, REMOVE_OPERATION, null); } @Override public void removeExternalRemoteConnector(String connectorName) { ModelNode address = getSubsystemAddress() .add("remote-connector", connectorName); executeOperation(address, REMOVE_OPERATION, null); } @Override public void enableMessagingTraces() { final ModelNode attributes = new ModelNode(); attributes.get("level").set("TRACE"); ModelNode address = PathAddress.parseCLIStyleAddress("/subsystem=logging/logger=org.wildfly.extension.messaging-activemq").toModelNode(); try { executeOperation(address, REMOVE_OPERATION, null); } catch (Exception e) { } executeOperation(address, ADD, attributes); address = PathAddress.parseCLIStyleAddress("/subsystem=logging/logger=org.apache.activemq.artemis").toModelNode(); try { executeOperation(address, REMOVE_OPERATION, null); } catch (Exception e) { } executeOperation(address, ADD, attributes); } @Override public void createRemoteConnector(String name, String socketBinding, Map<String, String> params) { ModelNode address = PathAddress.parseCLIStyleAddress(" /subsystem=messaging-activemq/server=default/remote-connector=" + name).toModelNode(); ModelNode attributes = new ModelNode(); attributes.get("socket-binding").set(socketBinding); if (params != null) { addParams(params, attributes); } try { executeOperation(address, REMOVE_OPERATION, null); } catch (Exception e) { } executeOperation(address, ADD, attributes); } @Override public void createSocketBinding(String name, String interfaceName, int port) { String interfaceValue = interfaceName == null || interfaceName.isEmpty() ? "public" : interfaceName; ModelNode address = PathAddress.parseCLIStyleAddress("/socket-binding-group=standard-sockets/socket-binding=" + name).toModelNode(); ModelNode attributes = new ModelNode(); attributes.get("interface").set(interfaceValue); attributes.get("port").set(port); try { executeOperation(address, REMOVE_OPERATION, null); } catch (Exception e) { } executeOperation(address, ADD, attributes); } @Override public boolean isRemoteBroker() { return false; } @Override public void disableSecurity() { final ModelNode operation = new ModelNode(); operation.get(OP).set(WRITE_ATTRIBUTE_OPERATION); operation.get(OP_ADDR).set(getServerAddress()); operation.get(NAME).set("security-enabled"); operation.get(VALUE).set(false); try { execute(client, operation); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void enableSecurity() { final ModelNode operation = new ModelNode(); operation.get(OP).set(WRITE_ATTRIBUTE_OPERATION); operation.get(OP_ADDR).set(getServerAddress()); operation.get(NAME).set("security-enabled"); operation.get(VALUE).set(true); try { execute(client, operation); } catch (Exception e) { throw new RuntimeException(e); } } }
16,754
36.483221
149
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/common/jms/JMSOperations.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.common.jms; import java.util.Map; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.dmr.ModelNode; /** * Utility to administrate Jakarta Messaging related resources on the server. An separate implementation should be created for * every possible Jakarta Messaging provider to be tested. * Use JMSOperationsProvider to get instances of implementing classes. * * Specify the fully qualified name of the activated implementation class in resources/jmsoperations.properties file. * @author <a href="jmartisk@redhat.com">Jan Martiska</a> */ public interface JMSOperations { ModelControllerClient getControllerClient(); ModelNode getServerAddress(); ModelNode getSubsystemAddress(); String getProviderName(); void createJmsQueue(final String queueName, final String jndiName); void createJmsQueue(final String queueName, final String jndiName, ModelNode attributes); void createJmsTopic(final String topicName, final String jndiName); void createJmsTopic(final String topicName, final String jndiName, ModelNode attributes); void removeJmsQueue(final String queueName); void removeJmsTopic(final String topicName); void addJmsConnectionFactory(final String name, final String jndiName, ModelNode attributes); void removeJmsConnectionFactory(final String name); void addJmsExternalConnectionFactory(final String name, final String jndiName, ModelNode attributes); void removeJmsExternalConnectionFactory(final String name); void addJmsBridge(String name, ModelNode attributes); void removeJmsBridge(String name); void addCoreBridge(String name, ModelNode attributes); void removeCoreBridge(String name); void addCoreQueue(final String queueName, final String queueAddress, boolean durable, String routing); void removeCoreQueue(final String queueName); /** * Creates remote acceptor * * @param name name of the remote acceptor * @param socketBinding name of socket binding * @param params params */ void createRemoteAcceptor(String name, String socketBinding, Map<String, String> params); /** * Remove remote acceptor * * @param name name of the remote acceptor */ void removeRemoteAcceptor(String name); /** * Creates remote connector * * @param name name of the remote connector * @param socketBinding name of socket binding * @param params params */ void createRemoteConnector(String name, String socketBinding, Map<String, String> params); void close(); void addHttpConnector(String connectorName, String socketBinding, String endpoint, Map<String, String> parameters); void removeHttpConnector(String connectorName); void addExternalHttpConnector(String connectorName, String socketBinding, String endpoint); void addExternalRemoteConnector(String name, String socketBinding); void removeExternalHttpConnector(String connectorName); void removeExternalRemoteConnector(String name); /** * Set system properties for the given destination and resourceAdapter. * * The system property for the given destination is {@code destination} and the one for the resourceAdapter is {@code resource.adapter}. */ void setSystemProperties(String destination, String resourceAdapter); void removeSystemProperties(); void enableMessagingTraces(); void createSocketBinding(String name, String interfaceName, int port); boolean isRemoteBroker(); void disableSecurity(); void enableSecurity(); }
4,717
32.942446
140
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/common/jms/JMSOperationsException.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.common.jms; /** * @author <a href="jmartisk@redhat.com">Jan Martiska</a> */ public class JMSOperationsException extends RuntimeException { JMSOperationsException(final String msg, final Throwable cause) { super(msg, cause); } JMSOperationsException(final String msg) { super(msg); } public JMSOperationsException(Throwable cause) { super(cause); } }
1,470
34.02381
70
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/common/jms/RemoteActiveMQProviderJMSOperations.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.common.jms; import static org.jboss.as.controller.client.helpers.ClientConstants.ADD; import static org.jboss.as.controller.client.helpers.ClientConstants.REMOVE_OPERATION; 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.integration.common.jms.JMSOperationsProvider.execute; import java.util.Map; import jakarta.jms.Connection; import jakarta.jms.JMSException; import jakarta.jms.Message; import jakarta.jms.Queue; import jakarta.jms.QueueRequestor; import jakarta.jms.QueueSession; import jakarta.jms.Session; import org.apache.activemq.artemis.api.core.RoutingType; import org.apache.activemq.artemis.api.core.management.ResourceNames; import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient; import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; /** * An implementation of JMSOperations for Apache ActiveMQ 6. * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc. */ public class RemoteActiveMQProviderJMSOperations implements JMSOperations { private final ModelControllerClient client; public RemoteActiveMQProviderJMSOperations(ModelControllerClient client) { this.client = client; } public RemoteActiveMQProviderJMSOperations(ManagementClient client) { this.client = client.getControllerClient(); } private static final ModelNode subsystemAddress = new ModelNode(); static { subsystemAddress.add("subsystem", "messaging-activemq"); } private static final ModelNode serverAddress = new ModelNode(); static { serverAddress.add("subsystem", "messaging-activemq"); serverAddress.add("server", "default"); } @Override public ModelControllerClient getControllerClient() { return client; } @Override public ModelNode getServerAddress() { return subsystemAddress.clone(); } @Override public ModelNode getSubsystemAddress() { return subsystemAddress.clone(); } @Override public String getProviderName() { return "activemq"; } @Override public void createJmsQueue(String queueName, String jndiName) { createJmsQueue(queueName, jndiName, new ModelNode()); } @Override public void createJmsQueue(String queueName, String jndiName, ModelNode attributes) { ModelNode address = getServerAddress() .add("external-jms-queue", queueName); attributes.get("entries").add(jndiName); executeOperation(address, ADD, attributes); createRemoteQueue("jms.queue." + queueName); } @Override public void createJmsTopic(String topicName, String jndiName) { createJmsTopic(topicName, jndiName, new ModelNode()); } @Override public void createJmsTopic(String topicName, String jndiName, ModelNode attributes) { ModelNode address = getServerAddress() .add("external-jms-topic", topicName); attributes.get("entries").add(jndiName); executeOperation(address, ADD, attributes); createRemoteTopic("jms.topic." + topicName); } @Override public void removeJmsQueue(String queueName) { ModelNode address = getServerAddress() .add("external-jms-queue", queueName); executeOperation(address, REMOVE_OPERATION, null); deleteRemoteQueue("jms.queue." + queueName); } @Override public void removeJmsTopic(String topicName) { ModelNode address = getServerAddress() .add("external-jms-topic", topicName); executeOperation(address, REMOVE_OPERATION, null); deleteRemoteTopic("jms.topic." + topicName); } @Override public void addJmsConnectionFactory(String name, String jndiName, ModelNode attributes) { ModelNode address = getServerAddress() .add("connection-factory", name); attributes.get("entries").add(jndiName); executeOperation(address, ADD, attributes); } @Override public void removeJmsConnectionFactory(String name) { ModelNode address = getServerAddress() .add("connection-factory", name); executeOperation(address, REMOVE_OPERATION, null); } @Override public void addJmsExternalConnectionFactory(String name, String jndiName, ModelNode attributes) { ModelNode address = getSubsystemAddress() .add("connection-factory", name); attributes.get("entries").add(jndiName); executeOperation(address, ADD, attributes); } @Override public void removeJmsExternalConnectionFactory(String name) { ModelNode address = getSubsystemAddress() .add("connection-factory", name); executeOperation(address, REMOVE_OPERATION, null); } @Override public void addJmsBridge(String name, ModelNode attributes) { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("jms-bridge", name); executeOperation(address, ADD, attributes); } @Override public void removeJmsBridge(String name) { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("jms-bridge", name); executeOperation(address, REMOVE_OPERATION, null); } @Override public void addCoreBridge(String name, ModelNode attributes) { ModelNode address = getServerAddress(); address.add("bridge", name); executeOperation(address, ADD, attributes); } @Override public void removeCoreBridge(String name) { ModelNode address = getServerAddress(); address.add("bridge", name); executeOperation(address, REMOVE_OPERATION, null); } @Override public void addCoreQueue(String queueName, String queueAddress, boolean durable, String routing) { ModelNode address = getServerAddress() .add("queue", queueName); ModelNode attributes = new ModelNode(); attributes.get("queue-address").set(queueAddress); attributes.get("durable").set(durable); attributes.get("routing-type").set(routing); executeOperation(address, ADD, attributes); } @Override public void removeCoreQueue(String queueName) { ModelNode address = getServerAddress() .add("queue", queueName); executeOperation(address, REMOVE_OPERATION, null); } @Override public void createRemoteAcceptor(String name, String socketBinding, Map<String, String> params) { ModelNode model = getServerAddress().add("remote-acceptor", name); ModelNode attributes = new ModelNode(); attributes.get("socket-binding").set(socketBinding); if (params != null) { addParams(params, model); } executeOperation(model, ADD, attributes); } private void addParams(Map<String, String> params, ModelNode model) { for (Map.Entry<String, String> entry : params.entrySet()) { model.get("params").add(entry.getKey(), entry.getValue()); } } @Override public void removeRemoteAcceptor(String name) { ModelNode model = getServerAddress().add("remote-acceptor", name); executeOperation(model, REMOVE_OPERATION, null); } @Override public void close() { // no-op // DO NOT close the management client. Whoever passed it into the constructor should close it } private void executeOperation(final ModelNode address, final String opName, ModelNode attributes) { final ModelNode operation = new ModelNode(); operation.get(OP).set(opName); operation.get(OP_ADDR).set(address); if (attributes != null) { for (Property property : attributes.asPropertyList()) { operation.get(property.getName()).set(property.getValue()); } } try { execute(client, operation); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void setSystemProperties(String destination, String resourceAdapter) { final ModelNode enableSubstitutionOp = new ModelNode(); enableSubstitutionOp.get(OP_ADDR).set(SUBSYSTEM, "ee"); enableSubstitutionOp.get(OP).set(WRITE_ATTRIBUTE_OPERATION); enableSubstitutionOp.get(NAME).set("annotation-property-replacement"); enableSubstitutionOp.get(VALUE).set(true); final ModelNode setDestinationOp = new ModelNode(); setDestinationOp.get(OP).set(ADD); setDestinationOp.get(OP_ADDR).add("system-property", "destination"); setDestinationOp.get("value").set(destination); final ModelNode setResourceAdapterOp = new ModelNode(); setResourceAdapterOp.get(OP).set(ADD); setResourceAdapterOp.get(OP_ADDR).add("system-property", "resource.adapter"); setResourceAdapterOp.get("value").set(resourceAdapter); try { execute(client, enableSubstitutionOp); execute(client, setDestinationOp); execute(client, setResourceAdapterOp); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void removeSystemProperties() { final ModelNode removeDestinationOp = new ModelNode(); removeDestinationOp.get(OP).set("remove"); removeDestinationOp.get(OP_ADDR).add("system-property", "destination"); final ModelNode removeResourceAdapterOp = new ModelNode(); removeResourceAdapterOp.get(OP).set("remove"); removeResourceAdapterOp.get(OP_ADDR).add("system-property", "resource.adapter"); final ModelNode disableSubstitutionOp = new ModelNode(); disableSubstitutionOp.get(OP_ADDR).set(SUBSYSTEM, "ee"); disableSubstitutionOp.get(OP).set(WRITE_ATTRIBUTE_OPERATION); disableSubstitutionOp.get(NAME).set("annotation-property-replacement"); disableSubstitutionOp.get(VALUE).set(false); try { execute(client, removeDestinationOp); execute(client, removeResourceAdapterOp); execute(client, disableSubstitutionOp); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void addHttpConnector(String connectorName, String socketBinding, String endpoint, Map<String, String> parameters) { ModelNode address = getServerAddress().add("http-connector", connectorName); ModelNode attributes = new ModelNode(); attributes.get("socket-binding").set(socketBinding); attributes.get("endpoint").set(endpoint); if (parameters != null && parameters.size() > 0) { ModelNode params = attributes.get("params").setEmptyList(); for (Map.Entry<String, String> param : parameters.entrySet()) { params.add(param.getKey(), param.getValue()); } } executeOperation(address, ADD, attributes); } @Override public void removeHttpConnector(String connectorName) { ModelNode address = getServerAddress() .add("http-connector", connectorName); executeOperation(address, REMOVE_OPERATION, null); } @Override public void addExternalHttpConnector(String connectorName, String socketBinding, String endpoint) { ModelNode address = getSubsystemAddress() .add("http-connector", connectorName); ModelNode attributes = new ModelNode(); attributes.get("socket-binding").set(socketBinding); attributes.get("endpoint").set(endpoint); executeOperation(address, ADD, attributes); } @Override public void addExternalRemoteConnector(String name, String socketBinding) { ModelNode address = getSubsystemAddress() .add("remote-connector", name); ModelNode attributes = new ModelNode(); attributes.get("socket-binding").set(socketBinding); executeOperation(address, ADD, attributes); } @Override public void removeExternalHttpConnector(String connectorName) { ModelNode address = getSubsystemAddress() .add("http-connector", connectorName); executeOperation(address, REMOVE_OPERATION, null); } @Override public void removeExternalRemoteConnector(String connectorName) { ModelNode address = getSubsystemAddress() .add("remote-connector", connectorName); executeOperation(address, REMOVE_OPERATION, null); } @Override public void enableMessagingTraces() { final ModelNode attributes = new ModelNode(); attributes.get("level").set("TRACE"); ModelNode address = PathAddress.parseCLIStyleAddress("/subsystem=logging/logger=org.wildfly.extension.messaging-activemq").toModelNode(); try { executeOperation(address, REMOVE_OPERATION, null); } catch (Exception e) { } executeOperation(address, ADD, attributes); address = PathAddress.parseCLIStyleAddress("/subsystem=logging/logger=org.apache.activemq.artemis").toModelNode(); try { executeOperation(address, REMOVE_OPERATION, null); } catch (Exception e) { } executeOperation(address, ADD, attributes); } @Override public void createRemoteConnector(String name, String socketBinding, Map<String, String> params) { ModelNode address = PathAddress.parseCLIStyleAddress(" /subsystem=messaging-activemq/server=default/remote-connector=" + name).toModelNode(); ModelNode attributes = new ModelNode(); attributes.get("socket-binding").set(socketBinding); if (params != null) { addParams(params, attributes); } try { executeOperation(address, REMOVE_OPERATION, null); } catch (Exception e) { } executeOperation(address, ADD, attributes); } @Override public void createSocketBinding(String name, String interfaceName, int port) { String interfaceValue = interfaceName == null || interfaceName.isEmpty() ? "public" : interfaceName; ModelNode address = PathAddress.parseCLIStyleAddress("/socket-binding-group=standard-sockets/socket-binding=" + name).toModelNode(); ModelNode attributes = new ModelNode(); attributes.get("interface").set(interfaceValue); attributes.get("port").set(port); try { executeOperation(address, REMOVE_OPERATION, null); } catch (Exception e) { } executeOperation(address, ADD, attributes); } private void createRemoteQueue(String queueName) { ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616", "guest", "guest"); try (Connection connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)) { connection.start(); Queue managementQueue = ActiveMQJMSClient.createQueue("activemq.management"); QueueRequestor requestor = new QueueRequestor((QueueSession) session, managementQueue); Message m = session.createMessage(); org.apache.activemq.artemis.api.jms.management.JMSManagementHelper.putOperationInvocation(m, ResourceNames.BROKER, "createQueue", queueName, queueName, true, RoutingType.ANYCAST.name()); Message reply = requestor.request(m); System.out.println("Creating queue " + queueName + " returned " + reply); if (!reply.getBooleanProperty("_AMQ_OperationSucceeded")) { String body = reply.getBody(String.class); if (!destinationAlreadyExist(body)) { System.out.println("Creation of queue " + queueName + " has failed because of " + body); } } } catch (JMSException ex) { ex.printStackTrace(); throw new JMSOperationsException(ex); } System.out.println("Queue " + queueName + " has been created"); } private void deleteRemoteQueue(String queueName) { ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616", "guest", "guest"); try (Connection connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)) { connection.start(); Queue managementQueue = ActiveMQJMSClient.createQueue("activemq.management"); QueueRequestor requestor = new QueueRequestor((QueueSession) session, managementQueue); Message m = session.createMessage(); org.apache.activemq.artemis.api.jms.management.JMSManagementHelper.putOperationInvocation(m, ResourceNames.BROKER, "destroyQueue", queueName, true, true); Message reply = requestor.request(m); System.out.println("Deleting queue " + queueName + " returned " + reply); if (!reply.getBooleanProperty("_AMQ_OperationSucceeded")) { String body = reply.getBody(String.class); System.out.println("Deleting of queue " + queueName + " has failed because of " + body); } } catch (JMSException ex) { ex.printStackTrace(); throw new JMSOperationsException(ex); } System.out.println("Queue " + queueName + " has been deleted"); } private boolean destinationAlreadyExist(String body) { return body.contains("AMQ119019") || body.contains("AMQ119018") || body.contains("AMQ229019") || body.contains("AMQ229018"); } private void createRemoteTopic(String topicName) { ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616", "guest", "guest"); try (Connection connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)) { connection.start(); Queue managementQueue = ActiveMQJMSClient.createQueue("activemq.management"); QueueRequestor requestor = new QueueRequestor((QueueSession) session, managementQueue); Message m = session.createMessage(); org.apache.activemq.artemis.api.jms.management.JMSManagementHelper.putOperationInvocation(m, ResourceNames.BROKER, "createAddress", topicName, RoutingType.MULTICAST.name()); Message reply = requestor.request(m); System.out.println("Creating topic " + topicName + " returned " + reply); if (!reply.getBooleanProperty("_AMQ_OperationSucceeded")) { String body = reply.getBody(String.class); if (!destinationAlreadyExist(body)) { System.out.println("Creation of topic " + topicName + " has failed because of " + body); throw new JMSOperationsException("Creation of topic " + topicName + " has failed because of " + body); } } } catch (JMSException ex) { ex.printStackTrace(); throw new JMSOperationsException(ex); } System.out.println("Topic " + topicName + " has been created"); } private void deleteRemoteTopic(String topicName) { ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616", "guest", "guest"); try (Connection connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)) { connection.start(); Queue managementQueue = ActiveMQJMSClient.createQueue("activemq.management"); QueueRequestor requestor = new QueueRequestor((QueueSession) session, managementQueue); Message m = session.createMessage(); org.apache.activemq.artemis.api.jms.management.JMSManagementHelper.putOperationInvocation(m, ResourceNames.BROKER, "deleteAddress", topicName, true); Message reply = requestor.request(m); System.out.println("Deleting topic " + topicName + " returned " + reply); if (!reply.getBooleanProperty("_AMQ_OperationSucceeded")) { String body = reply.getBody(String.class); System.out.println("Deleting of topic " + topicName + " has failed because of " + body); } } catch (JMSException ex) { ex.printStackTrace(); throw new JMSOperationsException(ex); } System.out.println("Topic " + topicName + " has been deleted"); } @Override public boolean isRemoteBroker() { return true; } @Override public void disableSecurity() { final ModelNode operation = new ModelNode(); operation.get(OP).set(WRITE_ATTRIBUTE_OPERATION); operation.get(OP_ADDR).set(getServerAddress()); operation.get(NAME).set("security-enabled"); operation.get(VALUE).set(false); try { execute(client, operation); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void enableSecurity() { final ModelNode operation = new ModelNode(); operation.get(OP).set(WRITE_ATTRIBUTE_OPERATION); operation.get(OP_ADDR).set(getServerAddress()); operation.get(NAME).set("security-enabled"); operation.get(VALUE).set(true); try { execute(client, operation); } catch (Exception e) { throw new RuntimeException(e); } } }
23,441
41.010753
198
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/management/Listener.java
package org.jboss.as.test.integration.management; /** * Basic connectors * * @author Dominik Pospisil <dpospisi@redhat.com> * @author <a href="mailto:pskopek@redhat.com">Peter Skopek</a> */ public enum Listener { HTTP("http", "http", false), HTTPS("http", "https", true), AJP("ajp", "http", false); private final String name; private final String scheme; private final boolean secure; private Listener(String name, String scheme, boolean secure) { this.name = name; this.scheme = scheme; this.secure = secure; } public final String getName() { return name; } public final String getScheme() { return scheme; } public final boolean isSecure() { return secure; } }
780
19.552632
66
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/management/util/SecuredServlet.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.management.util; import java.io.IOException; import java.io.PrintWriter; import jakarta.annotation.security.DeclareRoles; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.HttpConstraint; import jakarta.servlet.annotation.ServletSecurity; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * * @author Dominik Pospisil <dpospisi@redhat.com> */ @WebServlet(urlPatterns={"/SecuredServlet"}) @DeclareRoles({"user"}) @ServletSecurity(@HttpConstraint(rolesAllowed={"user"})) public class SecuredServlet extends HttpServlet { 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>SecuredServlet</title></head>"); out.println("<body>Done</body>"); out.println("</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,557
37.757576
91
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/management/util/WebUtil.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.jboss.as.test.integration.management.util; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit; import org.jboss.as.test.integration.common.HttpRequest; /** * @author dpospisi */ public class WebUtil { public static boolean testHttpURL(String url) { boolean failed = false; try { HttpRequest.get(url, 10, TimeUnit.SECONDS); } catch (Exception e) { failed = true; } return !failed; } public static String getBaseURL(URL url) throws MalformedURLException { return new URL(url.getProtocol(), url.getHost(), url.getPort(), "/").toString(); } }
792
23.78125
88
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/management/util/SimpleServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.util; import java.io.IOException; import java.io.PrintWriter; 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; /** * * @author Dominik Pospisil <dpospisi@redhat.com> */ @WebServlet(urlPatterns={"/SimpleServlet"}) public class SimpleServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); final PrintWriter out = response.getWriter(); final String envEntry = request.getParameter("env-entry"); if(envEntry == null) { out.println("<html>"); out.println("<head><title>SimpleServlet</title></head>"); out.println("<body>Done</body>"); out.println("</html>"); } else { InitialContext ctx = null; try { ctx = new InitialContext(); out.println(ctx.lookup("java:comp//env/" + envEntry)); ctx.close(); } catch (NamingException e) { e.printStackTrace(out); } finally { if(ctx != null) { try { ctx.close(); } catch (NamingException e) { } } } } 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,051
36.219512
91
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/management/util/SimpleHelloWorldServlet.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.jboss.as.test.integration.management.util; import java.io.IOException; import java.io.PrintWriter; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * * @author <a href="mailto:ehugonne@redhat.com">Emmanuel Hugonnet</a> (c) 2013 Red Hat, inc. */ public class SimpleHelloWorldServlet extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>SimpleHelloWorldServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet SimpleHelloWorldServlet at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
3,002
32.741573
123
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/management/util/PropertiesServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.util; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import java.util.Properties; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * A simple servlet that returns the JVM system properties. * * @author <a href="mailto:yborgess@redhat.com">Yeray Borges</a> */ @WebServlet(urlPatterns = {PropertiesServlet.SERVLET_PATH}) public class PropertiesServlet extends HttpServlet { public static final String SERVLET_PATH = "/propServletPath"; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { Properties p = System.getProperties(); Enumeration keys = p.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); String value = (String) p.get(key); out.println(key + "=" + value); } } finally { out.close(); } } }
2,368
37.209677
121
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/management/jca/DsMgmtTestBase.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.management.jca; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.dmr.ModelNode; /** * Extension of AbstractMgmtTestBase for data source testing. * * @author <a href="mailto:vrastsel@redhat.com">Vladimir Rastseluev</a> */ public class DsMgmtTestBase extends ContainerResourceMgmtTestBase { public static ModelNode baseAddress; public static void setBaseAddress(String dsType, String dsName) { baseAddress = new ModelNode(); baseAddress.add("subsystem", "datasources"); baseAddress.add(dsType, dsName); baseAddress.protect(); } //@After - called after each test protected void removeDs() throws Exception { final ModelNode removeOperation = Operations.createRemoveOperation(baseAddress); removeOperation.get(ModelDescriptionConstants.OPERATION_HEADERS).get("allow-resource-service-restart").set(true); executeOperation(removeOperation); } protected ModelNode readAttribute(ModelNode address, String attribute) throws Exception { final ModelNode operation = new ModelNode(); operation.get(OP).set("read-attribute"); operation.get("name").set(attribute); operation.get(OP_ADDR).set(address); return executeOperation(operation); } private void testCon(final String dsName, String type) throws Exception { final ModelNode address = new ModelNode(); address.add("subsystem", "datasources"); address.add(type, dsName); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("test-connection-in-pool"); operation.get(OP_ADDR).set(address); executeOperation(operation); } protected void testConnection(final String dsName) throws Exception { testCon(dsName, "data-source"); } protected void testConnectionXA(final String dsName) throws Exception { testCon(dsName, "xa-data-source"); } }
3,367
38.162791
121
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/management/jca/ComplexPropertiesParseUtils.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.management.jca; import java.security.InvalidParameterException; import java.util.Enumeration; import java.util.Properties; import org.jboss.dmr.ModelNode; /** * Common utility class for parsing operation tests * * @author <a href="vrastsel@redhat.com">Vladimir Rastseluev</a> * @author Flavia Rainone */ public class ComplexPropertiesParseUtils { /** * Returns common properties for both XA and Non-XA datasource * * @param jndiName jndi name * @param connectionSecurityType the connection security that will be configured in the properties */ public static Properties commonDsProperties(String jndiName, ConnectionSecurityType connectionSecurityType) { Properties params = new Properties(); //attributes params.put("use-java-context", "true"); params.put("spy", "false"); params.put("use-ccm", "true"); params.put("jndi-name", jndiName); //common elements params.put("driver-name", "h2"); params.put("new-connection-sql", "select 1"); params.put("transaction-isolation", "TRANSACTION_READ_COMMITTED"); params.put("url-delimiter", ":"); params.put("url-selector-strategy-class-name", "someClass"); //pool params.put("min-pool-size", "1"); params.put("max-pool-size", "5"); params.put("pool-prefill", "true"); params.put("pool-use-strict-min", "true"); params.put("flush-strategy", "EntirePool"); //security switch(connectionSecurityType) { case ELYTRON_AUTHENTICATION_CONTEXT: params.put("authentication-context", "HsqlAuthCtxt"); // fall thru! case ELYTRON: params.put("elytron-enabled", "true"); break; case SECURITY_DOMAIN: params.put("security-domain", "HsqlDbRealm"); break; case USER_PASSWORD: params.put("user-name", "sa"); params.put("password", "sa"); break; default: throw new InvalidParameterException("Unsupported security connection type for data sources: " + connectionSecurityType); } params.put("reauth-plugin-class-name", "someClass1"); //validation params.put("valid-connection-checker-class-name", "someClass2"); params.put("check-valid-connection-sql", "select 1"); params.put("validate-on-match", "true"); params.put("background-validation", "true"); params.put("background-validation-millis", "2000"); params.put("use-fast-fail", "true"); params.put("stale-connection-checker-class-name", "someClass3"); params.put("exception-sorter-class-name", "someClass4"); //time-out params.put("blocking-timeout-wait-millis", "20000"); params.put("idle-timeout-minutes", "4"); params.put("set-tx-query-timeout", "true"); params.put("query-timeout", "120"); params.put("use-try-lock", "100"); params.put("allocation-retry", "2"); params.put("allocation-retry-wait-millis", "3000"); //statement params.put("track-statements", "nowarn"); params.put("prepared-statements-cache-size", "30"); params.put("share-prepared-statements", "true"); return params; } /** * Returns properties for complex XA datasource * * @param jndiName jndi name * @param connectionSecurityType the connection security that will be configured in the properties */ public static Properties xaDsProperties(String jndiName, ConnectionSecurityType connectionSecurityType) { Properties params = commonDsProperties(jndiName, connectionSecurityType); //attributes //common params.put("xa-datasource-class", "org.jboss.as.connector.subsystems.datasources.ModifiableXaDataSource"); //xa-pool params.put("same-rm-override", "true"); params.put("interleaving", "true"); params.put("no-tx-separate-pool", "true"); params.put("pad-xid", "true"); params.put("wrap-xa-resource", "true"); //time-out params.put("xa-resource-timeout", "120"); //recovery params.put("no-recovery", "false"); params.put("recovery-plugin-class-name", "someClass5"); switch (connectionSecurityType) { case ELYTRON_AUTHENTICATION_CONTEXT: params.put("recovery-authentication-context", "HsqlAuthCtxt"); // fall thru! case ELYTRON: params.put("recovery-elytron-enabled", "true"); break; case SECURITY_DOMAIN: params.put("recovery-security-domain", "HsqlDbRealm"); break; case USER_PASSWORD: params.put("recovery-username", "sa"); params.put("recovery-password", "sa"); break; default: throw new InvalidParameterException("Unsupported connection security for data sources: " + connectionSecurityType); } return params; } /** * Returns properties for non XA datasource * * @param jndiName jndi name * @param connectionSecurityType the connection security that will be configured in the properties */ public static Properties nonXaDsProperties(String jndiName, ConnectionSecurityType connectionSecurityType) { Properties params = commonDsProperties(jndiName, connectionSecurityType); //attributes params.put("jta", "false"); //common params.put("driver-class", "org.hsqldb.jdbcDriver"); params.put("datasource-class", "org.jboss.as.connector.subsystems.datasources.ModifiableDataSource"); params.put("connection-url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); return params; } /** * Returns common properties for resource-adapter element */ public static Properties raCommonProperties() { Properties params = new Properties(); params.put("archive", "some.rar"); params.put("transaction-support", "XATransaction"); params.put("bootstrap-context", "default"); return params; } /** * Returns properties for RA connection-definition element * @param connectionSecurityType the connection security that will be configured in the properties * @param recoverySecurityType the connection recovery security that will be configured in the properties */ public static Properties raConnectionProperties(ConnectionSecurityType connectionSecurityType, ConnectionSecurityType recoverySecurityType) { Properties params = new Properties(); //attributes params.put("use-java-context", "false"); params.put("class-name", "Class1"); params.put("use-ccm", "true"); params.put("jndi-name", "java:jboss/name1"); params.put("enabled", "false"); //pool params.put("min-pool-size", "1"); params.put("max-pool-size", "5"); params.put("pool-prefill", "true"); params.put("pool-use-strict-min", "true"); params.put("flush-strategy", "IdleConnections"); //xa-pool params.put("same-rm-override", "true"); params.put("interleaving", "true"); params.put("no-tx-separate-pool", "true"); params.put("pad-xid", "true"); params.put("wrap-xa-resource", "true"); //security switch (connectionSecurityType) { case APPLICATION: params.put("security-application", "true"); break; case SECURITY_DOMAIN: params.put("security-domain", "SecRealm"); break; case SECURITY_DOMAIN_AND_APPLICATION: params.put("security-domain-and-application", "SecAndAppRealm"); break; case ELYTRON: params.put("elytron-enabled", "true"); break; case ELYTRON_AUTHENTICATION_CONTEXT: params.put("elytron-enabled", "true"); params.put("authentication-context", "AuthCtxt"); break; case ELYTRON_AUTHENTICATION_CONTEXT_AND_APPLICATION: params.put("elytron-enabled", "true"); params.put("authentication-context-and-application", "AuthCtxtAndApp"); break; default: throw new InvalidParameterException("Unsupported connection security type for rars: " + connectionSecurityType); } //validation params.put("background-validation", "true"); params.put("background-validation-millis", "5000"); params.put("use-fast-fail", "true"); //time-out params.put("blocking-timeout-wait-millis", "5000"); params.put("idle-timeout-minutes", "4"); params.put("allocation-retry", "2"); params.put("allocation-retry-wait-millis", "3000"); params.put("xa-resource-timeout", "300"); //recovery params.put("no-recovery", "false"); params.put("recovery-plugin-class-name", "someClass2"); if (recoverySecurityType != null) switch (recoverySecurityType) { case USER_PASSWORD: params.put("recovery-username", "sa"); params.put("recovery-password", "sa-pass"); break; case SECURITY_DOMAIN: params.put("recovery-security-domain", "SecRealm"); break; case ELYTRON: params.put("recovery-elytron-enabled", "true"); break; case ELYTRON_AUTHENTICATION_CONTEXT: params.put("recovery-elytron-enabled", "true"); params.put("recovery-authentication-context", "AuthCtxt"); break; default: throw new InvalidParameterException("Unsupported connection recovery security type for rars: " + connectionSecurityType); } return params; } /** * Returns properties for RA admin-object element */ public static Properties raAdminProperties() { Properties params = new Properties(); //attributes params.put("use-java-context", "true"); params.put("class-name", "Class3"); params.put("jndi-name", "java:jboss/Name3"); params.put("enabled", "true"); return params; } /** * Sets parameters for DMR operation * * @param operation * @param params */ public static void setOperationParams(ModelNode operation, Properties params) { String str; Enumeration e = params.propertyNames(); while (e.hasMoreElements()) { str = (String) e.nextElement(); operation.get(str).set(params.getProperty(str)); } } /** * Adds properties of Extension type to the operation * TODO: not implemented jet in DMR */ public static void addExtensionProperties(ModelNode operation) { operation.get("reauth-plugin-properties", "name").set("Property1"); operation.get("valid-connection-checker-properties", "name").set("Property2"); operation.get("stale-connection-checker-properties", "name").set("Property3"); operation.get("exception-sorter-properties", "name").set("Property4"); } /** * Checks if result of re-parsing contains certain parameters * * @param node * @param params * @returns boolean whether the node is ok */ public static boolean checkModelParams(ModelNode node, Properties params) { if (node == null) return false; String str, par; Enumeration e = params.propertyNames(); while (e.hasMoreElements()) { str = (String) e.nextElement(); par = params.getProperty(str); if (node.get(str) == null) return false; else { if (!node.get(str).asString().equals(par)) return false; } } return true; } }
13,470
39.332335
116
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/management/jca/ConnectionSecurityType.java
/* * Copyright 2017 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.management.jca; /** * Type of connection security. * * @author Flavia Rainone */ public enum ConnectionSecurityType { // PicketBox security domain SECURITY_DOMAIN, // PicketBox security domain and application SECURITY_DOMAIN_AND_APPLICATION, // Application managed security APPLICATION, // Elytron managed security, with current authentication context ELYTRON, // Elytron managed security, with specified authentication context ELYTRON_AUTHENTICATION_CONTEXT, // Elytron and Application managed security, with specified authentication context ELYTRON_AUTHENTICATION_CONTEXT_AND_APPLICATION, // user name and password USER_PASSWORD }
1,327
33.051282
86
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/management/base/AbstractExpressionSupportTestCase.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.management.base; import org.jboss.arquillian.container.test.api.ContainerController; 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.PathElement; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.dmr.Property; import org.jboss.dmr.ValueExpression; import org.jboss.logging.Logger; import org.junit.Assert; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ACCESS_TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALTERNATIVES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CHILDREN; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CHILD_TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXPRESSIONS_ALLOWED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_DEFAULTS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_CHILDREN_NAMES_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_DESCRIPTION_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REQUIRES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STORAGE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE_TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION; import static org.jboss.as.test.integration.domain.management.util.DomainTestUtils.createOperation; import static org.jboss.as.test.integration.domain.management.util.DomainTestUtils.executeForResult; /** * Smoke test of expression support. * * @author Ivan Straka (c) 2020 Red Hat Inc. */ public abstract class AbstractExpressionSupportTestCase { private static final Logger LOGGER = Logger.getLogger(AbstractExpressionSupportTestCase.class); private static final Set<ModelType> COMPLEX_TYPES = Collections.unmodifiableSet(EnumSet.of(ModelType.LIST, ModelType.OBJECT, ModelType.PROPERTY)); private final boolean immediateValidation = Boolean.getBoolean("immediate.expression.validation"); private final boolean logHandling = Boolean.getBoolean("expression.logging"); @ArquillianResource protected ContainerController container; private int conflicts; private int noSimple; private int noSimpleCollection; private int noComplexList; private int noObject; private int noComplexProperty; private int supportedUndefined; private int simple; private int simpleCollection; private int complexList; private int object; private int complexProperty; private ManagementClient managementClient; protected static ManagementClient createManagementClient() { return new ManagementClient( TestSuiteEnvironment.getModelControllerClient(), TestSuiteEnvironment.formatPossibleIpv6Address(TestSuiteEnvironment.getServerAddress()), TestSuiteEnvironment.getServerPort(), "remote+http"); } /** * Launch a primary HC in --admin-only. Iterate through all resources, converting any writable attribute that * support expressions and has a value or a default value to an expression (if it isn't already one), using the * value/default value as the expression default (so setting a system property isn't required). Then reload out of * --admin-only and confirm that the server start correctly. Finally, read the resources from the host * and confirm that the expected values are there. * * @throws Exception if there is one */ public void test(ManagementClient managementClient) throws Exception { this.managementClient = managementClient; conflicts = noSimple = noSimpleCollection = noComplexList = noComplexProperty = noObject = noComplexProperty = supportedUndefined = simple = simpleCollection = object = complexProperty = complexList = 0; Map<PathAddress, Map<String, ModelNode>> expectedValues = new HashMap<PathAddress, Map<String, ModelNode>>(); setExpressions(PathAddress.EMPTY_ADDRESS, expectedValues); LOGGER.debug("Update statistics:"); LOGGER.debug("=================="); LOGGER.debug("conflicts: " + conflicts); LOGGER.debug("no expression simple: " + noSimple); LOGGER.debug("no expression simple collection: " + noSimpleCollection); LOGGER.debug("no expression complex list: " + noComplexList); LOGGER.debug("no expression object: " + noObject); LOGGER.debug("no expression complex property: " + noComplexProperty); LOGGER.debug("supported but undefined: " + supportedUndefined); LOGGER.debug("simple: " + simple); LOGGER.debug("simple collection: " + simpleCollection); LOGGER.debug("complex list: " + complexList); LOGGER.debug("object: " + object); LOGGER.debug("complex property: " + complexProperty); restartContainer(); validateExpectedValues(PathAddress.EMPTY_ADDRESS, expectedValues); } protected void restartContainer() { ServerReload.executeReloadAndWaitForCompletion(managementClient); } private void setExpressions(PathAddress address, Map<PathAddress, Map<String, ModelNode>> expectedValues) throws IOException, MgmtOperationException { ModelNode description = readResourceDescription(address); ModelNode resource = readResource(address, true, false); ModelNode resourceNoDefaults = readResource(address, false, false); Map<String, ModelNode> expressionAttrs = new HashMap<String, ModelNode>(); Map<String, ModelNode> otherAttrs = new HashMap<String, ModelNode>(); Map<String, ModelNode> expectedAttrs = new HashMap<String, ModelNode>(); organizeAttributes(address, description, resource, resourceNoDefaults, expressionAttrs, otherAttrs, expectedAttrs); for (Map.Entry<String, ModelNode> entry : expressionAttrs.entrySet()) { writeAttribute(address, entry.getKey(), entry.getValue()); } // Set the other attrs as well just to exercise the write-attribute handlers for (Map.Entry<String, ModelNode> entry : otherAttrs.entrySet()) { writeAttribute(address, entry.getKey(), entry.getValue()); } if (expectedAttrs.size() > 0 && immediateValidation) { // Validate that our write-attribute calls resulted in the expected values in the model ModelNode modifiedResource = readResource(address, true, true); for (Map.Entry<String, ModelNode> entry : expectedAttrs.entrySet()) { ModelNode expectedValue = entry.getValue(); ModelNode modVal = modifiedResource.get(entry.getKey()); validateAttributeValue(address, entry.getKey(), expectedValue, modVal); } } // Store the modified values for confirmation after HC reload expectedValues.put(address, expectedAttrs); // Recurse into children, being careful about what processes we are touching for (Property descProp : description.get(CHILDREN).asPropertyList()) { String childType = descProp.getName(); List<String> children = readChildrenNames(address, childType); for (String child : children) { setExpressions(address.append(PathElement.pathElement(childType, child)), expectedValues); } } } private void organizeAttributes(PathAddress address, ModelNode description, ModelNode resource, ModelNode resourceNoDefaults, Map<String, ModelNode> expressionAttrs, Map<String, ModelNode> otherAttrs, Map<String, ModelNode> expectedAttrs) { ModelNode attributeDescriptions = description.get(ATTRIBUTES); for (Property descProp : attributeDescriptions.asPropertyList()) { String attrName = descProp.getName(); ModelNode attrDesc = descProp.getValue(); if (isAttributeExcluded(address, attrName, attrDesc, resourceNoDefaults)) { continue; } ModelNode noDefaultValue = resourceNoDefaults.get(attrName); if (!noDefaultValue.isDefined()) { // We need to see if it's legal to set this attribute, or whether it's undefined // because an alternative attribute is defined or a required attribute is not defined. Set<String> base = new HashSet<String>(); base.add(attrName); if (attrDesc.hasDefined(REQUIRES)) { for (ModelNode node : attrDesc.get(REQUIRES).asList()) { base.add(node.asString()); } } boolean conflict = false; for (String baseAttr : base) { if (!resource.hasDefined(baseAttr)) { conflict = true; break; } ModelNode baseAttrAlts = attributeDescriptions.get(baseAttr, ALTERNATIVES); if (baseAttrAlts.isDefined()) { for (ModelNode alt : baseAttrAlts.asList()) { String altName = alt.asString(); if (resourceNoDefaults.hasDefined(alt.asString()) || expressionAttrs.containsKey(altName) || otherAttrs.containsKey(altName)) { conflict = true; break; } } } } if (conflict) { conflicts++; logHandling("Skipping conflicted attribute " + attrName + " at " + address.toModelNode().asString()); continue; } } ModelNode attrValue = resource.get(attrName); ModelType attrType = attrValue.getType(); if (attrDesc.get(EXPRESSIONS_ALLOWED).asBoolean(false)) { // If it's defined and not an expression, use the current value to create an expression if (attrType != ModelType.UNDEFINED && attrType != ModelType.EXPRESSION) { // Deal with complex types specially if (COMPLEX_TYPES.contains(attrType)) { ModelNode valueType = attrDesc.get(VALUE_TYPE); if (valueType.getType() == ModelType.TYPE) { // Simple collection whose elements support expressions handleSimpleCollection(address, attrName, attrValue, valueType.asType(), expressionAttrs, otherAttrs, expectedAttrs); } else if (valueType.isDefined()) { handleComplexCollection(address, attrName, attrValue, attrType, valueType, expressionAttrs, otherAttrs, expectedAttrs); } else { noSimple++; logNoExpressions(address, attrName); otherAttrs.put(attrName, attrValue); expectedAttrs.put(attrName, attrValue); } } else { if (attrType == ModelType.STRING) { checkForUnconvertedExpression(address, attrName, attrValue); } String expression = "${exp.test:" + attrValue.asString() + "}"; expressionAttrs.put(attrName, new ModelNode(expression)); expectedAttrs.put(attrName, new ModelNode().set(new ValueExpression(expression))); simple++; logHandling("Added expression to simple attribute " + attrName + " at " + address.toModelNode().asString()); } } else { if (attrType != ModelType.EXPRESSION) { supportedUndefined++; logHandling("Expression supported but value undefined on simple attribute " + attrName + " at " + address.toModelNode().asString()); } else { simple++; logHandling("Already found an expression on simple attribute " + attrName + " at " + address.toModelNode().asString()); } otherAttrs.put(attrName, attrValue); expectedAttrs.put(attrName, attrValue); } } else if (COMPLEX_TYPES.contains(attrType) && attrDesc.get(VALUE_TYPE).getType() != ModelType.TYPE && attrDesc.get(VALUE_TYPE).isDefined()) { handleComplexCollection(address, attrName, attrValue, attrType, attrDesc.get(VALUE_TYPE), expressionAttrs, otherAttrs, expectedAttrs); } else /*if (!attrDesc.hasDefined(DEPRECATED))*/ { noSimple++; logNoExpressions(address, attrName); otherAttrs.put(attrName, attrValue); expectedAttrs.put(attrName, attrValue); } } } private boolean isAttributeExcluded(PathAddress address, String attrName, ModelNode attrDesc, ModelNode resourceNoDefaults) { if (!attrDesc.get(ACCESS_TYPE).isDefined() || !attrDesc.get(ACCESS_TYPE).asString().equalsIgnoreCase("read-write")) { return true; } if (attrDesc.get(STORAGE).isDefined() && !attrDesc.get(STORAGE).asString().equalsIgnoreCase("configuration")) { return true; } if (attrDesc.get(ModelDescriptionConstants.DEPRECATED).isDefined()) { return true; } // Special cases if ("default-web-module".equals(attrName)) { if (address.size() > 1) { PathElement subPe = address.getElement(0); if ("subsystem".equals(subPe.getKey()) && "web".equals(subPe.getValue()) && "virtual-server".equals(address.getLastElement().getKey())) { // This is not allowed if "enable-welcome-root" is "true", which is overly complex to validate // so skip it return true; } } } else if ("policy-modules".equals(attrName) || "login-modules".equals(attrName)) { if (address.size() > 2) { PathElement subPe = address.getElement(0); if ("subsystem".equals(subPe.getKey()) && "security".equals(subPe.getValue()) && "security-domain".equals(address.getElement(1).getKey())) { // This is a kind of alias that shows child resources as a list. Validating it // after reload breaks because the real child resources get changed. It's deprecated, so // we could exclude all deprecated attributes, but for now I'd rather be specific return true; } } } else if ("virtual-nodes".equals(attrName)) { if (address.size() == 3) { PathElement subPe = address.getElement(0); PathElement containerPe = address.getElement(1); PathElement distPe = address.getElement(2); if ("subsystem".equals(subPe.getKey()) && "infinispan".equals(subPe.getValue()) && "cache-container".equals(containerPe.getKey()) && "distributed-cache".equals(distPe.getKey())) { // This is a distributed cache attribute in Infinispan which has been deprecated return true; } } } else if (address.size() > 0 && "transactions".equals(address.getLastElement().getValue()) && "subsystem".equals(address.getLastElement().getKey())) { if (attrName.contains("jdbc")) { // Ignore jdbc store attributes unless jdbc store is enabled return !resourceNoDefaults.hasDefined("use-jdbc-store") || !resourceNoDefaults.get("use-jdbc-store").asBoolean(); } else if (attrName.contains("journal")) { // Ignore journal store attributes unless journal store is enabled return !resourceNoDefaults.hasDefined("use-journal-store") || !resourceNoDefaults.get("use-journal-store").asBoolean(); } } else if ("security-application".equals(attrName)) { if (address.size() == 3) { PathElement subPe = address.getElement(0); PathElement raPe = address.getElement(1); PathElement connPe = address.getElement(2); if ("subsystem".equals(subPe.getKey()) && "resource-adapters".equals(subPe.getValue()) && "resource-adapter".equals(raPe.getKey()) && "connection-definitions".equals(connPe.getKey())) { // todo ignore due to WFLY-14389 return true; } } } else if (attrName.startsWith("wm-security")) { if (address.size() == 2) { PathElement subPe = address.getElement(0); PathElement raPe = address.getElement(1); if ("subsystem".equals(subPe.getKey()) && "resource-adapters".equals(subPe.getValue()) && "resource-adapter".equals(raPe.getKey())) { // todo ignore due to WFLY-14387 return true; } } } else if ("transaction-support".equals(attrName)) { if (address.size() == 2) { PathElement subPe = address.getElement(0); PathElement raPe = address.getElement(1); if ("subsystem".equals(subPe.getKey()) && "resource-adapters".equals(subPe.getValue()) && "resource-adapter".equals(raPe.getKey())) { // todo ignore due to WFLY-14388 return true; } } } else if ("pool-fair".equals(attrName) || "pad-xid".equals(attrName) || "interleaving".equals(attrName) || "no-tx-separate-pool".equals(attrName) || "wrap-xa-resource".equals(attrName)) { if (address.size() == 3) { PathElement subPe = address.getElement(0); PathElement raPe = address.getElement(1); PathElement connPe = address.getElement(2); if ("subsystem".equals(subPe.getKey()) && "resource-adapters".equals(subPe.getValue()) && "resource-adapter".equals(raPe.getKey()) && "connection-definitions".equals(connPe.getKey())) { // todo ignore due to WFLY-14388 // (these attributes are not marshalled because transaction-spupport is used as a condition if // they should be masrshalled (and it is ignored) return true; } } } else if ("fixed-source-port".equals(attrName)) { if (address.size() == 2) { PathElement socketBindingGroupPe = address.getElement(0); PathElement remoteDestPe = address.getElement(1); if ("socket-binding-group".equals(socketBindingGroupPe.getKey()) && "remote-destination-outbound-socket-binding".equals(remoteDestPe.getKey())) { // todo ignore due to WFCORE-5257 return true; } } } else if ("console-enabled".equals(attrName)) { if (address.size() == 2) { PathElement coreServicePe = address.getElement(0); PathElement mngmtIfPe = address.getElement(1); if ("core-service".equals(coreServicePe.getKey()) && "management".equals(coreServicePe.getValue()) && "management-interface".equals(mngmtIfPe.getKey()) && "http-interface".equals(mngmtIfPe.getValue())) { // todo ignore due to WFCORE-5256 return true; } } } else if ("async-registration".equals(attrName)) { if (address.size() > 0) { PathElement coreServicePe = address.getElement(0); if ("subsystem".equals(coreServicePe.getKey()) && "xts".equals(coreServicePe.getValue())) { // todo ignore due to WFLY-14390 // moreover the subsystem is deprecated return true; } } } else if ("path".equals(attrName) && address.size() == 1 && "path".equals(address.getElement(0).getKey()) ) { // /path=xyz is a special case - access is read-write but does not matter // there is read-only attribute that holds the value: true (access is read-only) when the // path is set by the system and false if the path is set by a user try { return readAttribute(address, "read-only").asBoolean(); } catch (IOException | MgmtOperationException e) { throw new RuntimeException(e); } } return false; } private void logNoExpressions(PathAddress address, String attrName) { if (logHandling) { logHandling("No expression support for attribute " + attrName + " at " + address.toModelNode().asString()); } } private void logHandling(String msg) { if (logHandling) { LOGGER.info(msg); } } private void handleSimpleCollection(PathAddress address, String attrName, ModelNode attrValue, ModelType valueType, Map<String, ModelNode> expressionAttrs, Map<String, ModelNode> otherAttrs, Map<String, ModelNode> expectedAttrs) { if (COMPLEX_TYPES.contains(valueType)) { // Too complicated noSimpleCollection++; logNoExpressions(address, attrName); otherAttrs.put(attrName, attrValue); } else { boolean hasExpression = false; ModelNode updated = new ModelNode(); ModelNode expected = new ModelNode(); for (ModelNode item : attrValue.asList()) { ModelType itemType = item.getType(); if (itemType == ModelType.PROPERTY) { Property prop = item.asProperty(); ModelNode propVal = prop.getValue(); ModelType propValType = propVal.getType(); if (propVal.isDefined() && propValType != ModelType.EXPRESSION) { // Convert property value to expression if (propValType == ModelType.STRING) { checkForUnconvertedExpression(address, attrName, propVal); } String expression = "${exp.test:" + propVal.asString() + "}"; updated.get(prop.getName()).set(expression); expected.get(prop.getName()).set(new ModelNode().set(new ValueExpression(expression))); hasExpression = true; } else { updated.get(prop.getName()).set(propVal); expected.get(prop.getName()).set(propVal); } } else if (item.isDefined() && itemType != ModelType.EXPRESSION) { // Convert item to expression if (itemType == ModelType.STRING) { checkForUnconvertedExpression(address, attrName, item); } String expression = "${exp.test:" + item.asString() + "}"; updated.add(expression); expected.add(new ModelNode().set(new ValueExpression(expression))); hasExpression = true; } else { updated.add(item); expected.add(item); } } if (hasExpression) { simpleCollection++; logHandling("Added expression to SIMPLE " + attrValue.getType() + " attribute " + attrName + " at " + address.toModelNode().asString()); expressionAttrs.put(attrName, updated); expectedAttrs.put(attrName, expected); } else { // We didn't change anything noSimpleCollection++; logNoExpressions(address, attrName); otherAttrs.put(attrName, attrValue); expectedAttrs.put(attrName, attrValue); } } } private void handleComplexCollection(PathAddress address, String attrName, ModelNode attrValue, ModelType attrType, ModelNode valueTypeDesc, Map<String, ModelNode> expressionAttrs, Map<String, ModelNode> otherAttrs, Map<String, ModelNode> expectedAttrs) { switch (attrType) { case LIST: handleComplexList(address, attrName, attrValue, valueTypeDesc, expressionAttrs, otherAttrs, expectedAttrs); break; case OBJECT: handleComplexObject(address, attrName, attrValue, valueTypeDesc, expressionAttrs, otherAttrs, expectedAttrs); break; case PROPERTY: handleComplexProperty(address, attrName, attrValue, valueTypeDesc, expressionAttrs, otherAttrs, expectedAttrs); break; default: throw new IllegalArgumentException(attrType.toString()); } } private void handleComplexList(PathAddress address, String attrName, ModelNode attrValue, ModelNode valueTypeDesc, Map<String, ModelNode> expressionAttrs, Map<String, ModelNode> otherAttrs, Map<String, ModelNode> expectedAttrs) { ModelNode updatedList = new ModelNode().setEmptyList(); ModelNode expectedList = new ModelNode().setEmptyList(); boolean changed = false; for (ModelNode item : attrValue.asList()) { ModelNode updated = new ModelNode(); ModelNode toExpect = new ModelNode(); handleComplexItem(address, attrName, item, valueTypeDesc, updated, toExpect); changed |= !updated.equals(item); updatedList.add(updated); expectedList.add(toExpect); } if (changed) { complexList++; logHandling("Added expression to COMPLEX LIST attribute " + attrName + " at " + address.toModelNode().asString()); expressionAttrs.put(attrName, updatedList); expectedAttrs.put(attrName, expectedList); } else { noComplexList++; logNoExpressions(address, attrName); otherAttrs.put(attrName, attrValue); } } private void handleComplexObject(PathAddress address, String attrName, ModelNode attrValue, ModelNode valueTypeDesc, Map<String, ModelNode> expressionAttrs, Map<String, ModelNode> otherAttrs, Map<String, ModelNode> expectedAttrs) { ModelNode updated = new ModelNode(); ModelNode toExpect = new ModelNode(); handleComplexItem(address, attrName, attrValue, valueTypeDesc, updated, toExpect); if (!updated.equals(attrValue)) { object++; logHandling("Added expression to OBJECT attribute " + attrName + " at " + address.toModelNode().asString()); expressionAttrs.put(attrName, updated); expectedAttrs.put(attrName, toExpect); } else { noObject++; logNoExpressions(address, attrName); otherAttrs.put(attrName, attrValue); } } private void handleComplexProperty(PathAddress address, String attrName, ModelNode attrValue, ModelNode valueTypeDesc, Map<String, ModelNode> expressionAttrs, Map<String, ModelNode> otherAttrs, Map<String, ModelNode> expectedAttrs) { Property prop = attrValue.asProperty(); ModelNode propVal = prop.getValue(); ModelNode updatedPropVal = new ModelNode(); ModelNode propValToExpect = new ModelNode(); handleComplexItem(address, attrName, propVal, valueTypeDesc, updatedPropVal, propValToExpect); if (!updatedPropVal.equals(propVal)) { complexProperty++; ModelNode updatedProp = new ModelNode().set(prop.getName(), updatedPropVal); logHandling("Added expression to COMPLEX PROPERTY attribute " + attrName + " at " + address.toModelNode().asString()); expressionAttrs.put(attrName, updatedProp); expectedAttrs.put(attrName, new ModelNode().set(prop.getName(), propValToExpect)); } else { noComplexProperty++; logNoExpressions(address, attrName); otherAttrs.put(attrName, attrValue); } } private void handleComplexItem(PathAddress address, String attrName, ModelNode item, ModelNode valueTypeDesc, ModelNode updatedItem, ModelNode itemToExpect) { // Hack to deal with time unit processing Set<String> keys = valueTypeDesc.keys(); boolean timeAttr = keys.size() == 2 && keys.contains("time") && keys.contains("unit"); boolean changed = false; for (Property fieldProp : valueTypeDesc.asPropertyList()) { String fieldName = fieldProp.getName(); if (!item.has(fieldName)) { continue; } boolean timeunit = timeAttr && "unit".equals(fieldName); ModelNode fieldDesc = fieldProp.getValue(); ModelNode fieldValue = item.get(fieldName); ModelType valueType = fieldValue.getType(); if (valueType == ModelType.UNDEFINED || valueType == ModelType.EXPRESSION || COMPLEX_TYPES.contains(valueType) // too complex || !fieldDesc.get(EXPRESSIONS_ALLOWED).asBoolean(false)) { updatedItem.get(fieldName).set(fieldValue); itemToExpect.get(fieldName).set(fieldValue); } else { if (valueType == ModelType.STRING) { checkForUnconvertedExpression(address, attrName, item); } String valueString = timeunit ? fieldValue.asString().toLowerCase() : fieldValue.asString(); String expression = "${exp.test:" + valueString + "}"; updatedItem.get(fieldName).set(expression); itemToExpect.get(fieldName).set(new ModelNode().set(new ValueExpression(expression))); changed = true; } } if (!changed) { // Use unchanged 'item' updatedItem.set(item); itemToExpect.set(item); } } private ModelNode readResourceDescription(PathAddress address) throws IOException, MgmtOperationException { ModelNode op = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, address); return executeForResult(op, managementClient.getControllerClient()); } private ModelNode readResource(PathAddress address, boolean defaults, boolean failIfMissing) throws IOException, MgmtOperationException { try { ModelNode op = createOperation(READ_RESOURCE_OPERATION, address); op.get(INCLUDE_DEFAULTS).set(defaults); return executeForResult(op, managementClient.getControllerClient()); } catch (MgmtOperationException e) { if (failIfMissing) { throw e; } return new ModelNode(); } } private void checkForUnconvertedExpression(PathAddress address, String attrName, ModelNode attrValue) { String text = attrValue.asString(); int start = text.indexOf("${"); if (start > -1) { if (text.indexOf("}") > start) { Assert.fail(address + " attribute " + attrName + " is storing an unconverted expression: " + text); } } } private void writeAttribute(PathAddress address, String attrName, ModelNode value) throws IOException, MgmtOperationException { ModelNode op = createOperation(WRITE_ATTRIBUTE_OPERATION, address); op.get(NAME).set(attrName); op.get(VALUE).set(value); executeForResult(op, managementClient.getControllerClient()); } private ModelNode readAttribute(PathAddress address, String attrName) throws IOException, MgmtOperationException { ModelNode op = createOperation(READ_ATTRIBUTE_OPERATION, address); op.get(NAME).set(attrName); return executeForResult(op, managementClient.getControllerClient()); } private List<String> readChildrenNames(PathAddress address, String childType) throws IOException, MgmtOperationException { ModelNode op = createOperation(READ_CHILDREN_NAMES_OPERATION, address); op.get(CHILD_TYPE).set(childType); ModelNode opResult = executeForResult(op, managementClient.getControllerClient()); List<String> result = new ArrayList<String>(); for (ModelNode child : opResult.asList()) { result.add(child.asString()); } return result; } private void validateExpectedValues(PathAddress address, Map<PathAddress, Map<String, ModelNode>> expectedValues) throws IOException, MgmtOperationException { Map<String, ModelNode> expectedModel = expectedValues.get(address); if (expectedModel != null && isValidatable(address)) { ModelNode resource = readResource(address, true, true); for (Map.Entry<String, ModelNode> entry : expectedModel.entrySet()) { String attrName = entry.getKey(); ModelNode expectedValue = entry.getValue(); ModelNode modVal = resource.get(entry.getKey()); validateAttributeValue(address, attrName, expectedValue, modVal); } } ModelNode description = readResourceDescription(address); // Recurse into children for (Property descProp : description.get(CHILDREN).asPropertyList()) { String childType = descProp.getName(); List<String> children = readChildrenNames(address, childType); for (String child : children) { validateExpectedValues(address.append(PathElement.pathElement(childType, child)), expectedValues); } } } private void validateAttributeValue(PathAddress address, String attrName, ModelNode expectedValue, ModelNode modelValue) { switch (expectedValue.getType()) { case EXPRESSION: { Assert.assertEquals(address + " attribute " + attrName + " value " + modelValue + " is an unconverted expression", expectedValue, modelValue); break; } case INT: case LONG: Assert.assertTrue(address + " attribute " + attrName + " is a valid type", modelValue.getType() == ModelType.INT || modelValue.getType() == ModelType.LONG); Assert.assertEquals(address + " -- " + attrName, expectedValue.asLong(), modelValue.asLong()); break; default: { Assert.assertEquals(address + " -- " + attrName, expectedValue, modelValue); } } } private boolean isValidatable(PathAddress address) { boolean result = true; if (address.size() > 1 && address.getLastElement().getKey().equals("bootstrap-context") && address.getLastElement().getValue().equals("default") && address.getElement(address.size() - 2).getKey().equals("subsystem") && address.getElement(address.size() - 2).getValue().equals("jca")) { // JCA subsystem doesn't persist this resource result = false; } return result; } }
39,071
50.410526
172
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/management/base/AbstractMgmtServerSetupTask.java
package org.jboss.as.test.integration.management.base; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; /** * @author Stuart Douglas */ public abstract class AbstractMgmtServerSetupTask extends AbstractMgmtTestBase implements ServerSetupTask { private ManagementClient managementClient; @Override protected ModelControllerClient getModelControllerClient() { return managementClient.getControllerClient(); } @Override public final void setup(final ManagementClient managementClient, final String containerId) throws Exception { this.managementClient = managementClient; doSetup(managementClient); } protected abstract void doSetup(final ManagementClient managementClient) throws Exception; }
878
31.555556
113
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/management/base/ContainerResourceMgmtTestBase.java
package org.jboss.as.test.integration.management.base; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; /** * Class that is extended by management tests that can use resource injection to get the management client * * @author Stuart Douglas */ public abstract class ContainerResourceMgmtTestBase extends AbstractMgmtTestBase { @ContainerResource private ManagementClient managementClient; public ManagementClient getManagementClient() { return managementClient; } public void setManagementClient(ManagementClient managementClient) { this.managementClient = managementClient; } @Override protected ModelControllerClient getModelControllerClient() { return managementClient.getControllerClient(); } }
899
24.714286
106
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/ldap/InMemoryDirectoryServiceFactory.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.ldap; import java.io.File; import java.io.IOException; import java.util.List; import org.apache.commons.io.FileUtils; import org.apache.directory.api.ldap.model.constants.SchemaConstants; import org.apache.directory.api.ldap.model.schema.LdapComparator; import org.apache.directory.api.ldap.model.schema.SchemaManager; import org.apache.directory.api.ldap.model.schema.comparators.NormalizingComparator; import org.apache.directory.api.ldap.model.schema.registries.ComparatorRegistry; import org.apache.directory.api.ldap.model.schema.registries.SchemaLoader; import org.apache.directory.api.ldap.schema.loader.JarLdifSchemaLoader; import org.apache.directory.api.ldap.schema.manager.impl.DefaultSchemaManager; import org.apache.directory.api.util.exception.Exceptions; import org.apache.directory.server.constants.ServerDNConstants; import org.apache.directory.server.core.DefaultDirectoryService; import org.apache.directory.server.core.api.DirectoryService; import org.apache.directory.server.core.api.DnFactory; import org.apache.directory.server.core.api.InstanceLayout; import org.apache.directory.server.core.api.partition.Partition; import org.apache.directory.server.core.api.schema.SchemaPartition; import org.apache.directory.server.core.factory.AvlPartitionFactory; import org.apache.directory.server.core.factory.DirectoryServiceFactory; import org.apache.directory.server.core.factory.PartitionFactory; import org.apache.directory.server.core.shared.DefaultDnFactory; import org.apache.directory.server.i18n.I18n; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Factory for a fast (mostly in-memory-only) ApacheDS DirectoryService. Use only for tests!! * * @author Josef Cacek */ public class InMemoryDirectoryServiceFactory implements DirectoryServiceFactory { private static Logger LOG = LoggerFactory.getLogger(InMemoryDirectoryServiceFactory.class); private static volatile int counter = 1; private final DirectoryService directoryService; private final PartitionFactory partitionFactory; /** * Default constructor which creates {@link DefaultDirectoryService} instance and configures {@link AvlPartitionFactory} as * the {@link PartitionFactory} implementation. */ public InMemoryDirectoryServiceFactory() { try { directoryService = new DefaultDirectoryService(); } catch (Exception e) { throw new RuntimeException(e); } directoryService.setShutdownHookEnabled(false); partitionFactory = new AvlPartitionFactory(); } /** * Constructor which uses provided {@link DirectoryService} and {@link PartitionFactory} implementations. * * @param directoryService must be not-<code>null</code> * @param partitionFactory must be not-<code>null</code> */ public InMemoryDirectoryServiceFactory(DirectoryService directoryService, PartitionFactory partitionFactory) { this.directoryService = directoryService; this.partitionFactory = partitionFactory; } /** * {@inheritDoc} */ @Override public void init(String name) throws Exception { if ((directoryService == null) || directoryService.isStarted()) { return; } int id = counter++; directoryService.setInstanceId(name + id); // instance layout InstanceLayout instanceLayout = new InstanceLayout(System.getProperty("java.io.tmpdir") + "/server-work-" + directoryService.getInstanceId()); if (instanceLayout.getInstanceDirectory().exists()) { try { FileUtils.deleteDirectory(instanceLayout.getInstanceDirectory()); } catch (IOException e) { LOG.warn("couldn't delete the instance directory before initializing the DirectoryService", e); } } directoryService.setInstanceLayout(instanceLayout); // Init the schema // SchemaLoader loader = new SingleLdifSchemaLoader(); SchemaLoader loader = new JarLdifSchemaLoader(); SchemaManager schemaManager = new DefaultSchemaManager(loader); schemaManager.loadAllEnabled(); ComparatorRegistry comparatorRegistry = schemaManager.getComparatorRegistry(); for (LdapComparator<?> comparator : comparatorRegistry) { if (comparator instanceof NormalizingComparator) { ((NormalizingComparator) comparator).setOnServer(); } } directoryService.setSchemaManager(schemaManager); InMemorySchemaPartition inMemorySchemaPartition = new InMemorySchemaPartition(schemaManager); SchemaPartition schemaPartition = new SchemaPartition(schemaManager); schemaPartition.setWrappedPartition(inMemorySchemaPartition); directoryService.setSchemaPartition(schemaPartition); List<Throwable> errors = schemaManager.getErrors(); if (errors.size() != 0) { throw new Exception(I18n.err(I18n.ERR_317, Exceptions.printErrors(errors))); } DnFactory dnFactory = new DefaultDnFactory(schemaManager, 1024); // Init system partition Partition systemPartition = partitionFactory.createPartition(directoryService.getSchemaManager(), dnFactory, "system", ServerDNConstants.SYSTEM_DN, 500, new File(directoryService.getInstanceLayout().getPartitionsDirectory(), "system")); systemPartition.setSchemaManager(directoryService.getSchemaManager()); partitionFactory.addIndex(systemPartition, SchemaConstants.OBJECT_CLASS_AT, 100); directoryService.setSystemPartition(systemPartition); directoryService.startup(); } /** * {@inheritDoc} */ @Override public DirectoryService getDirectoryService() throws Exception { return directoryService; } /** * {@inheritDoc} */ @Override public PartitionFactory getPartitionFactory() throws Exception { return partitionFactory; } }
7,092
41.728916
150
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/ldap/InMemorySchemaPartition.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.ldap; import java.io.IOException; import java.net.URL; import java.util.Map; import java.util.TreeSet; import java.util.UUID; import java.util.regex.Pattern; import org.apache.directory.api.ldap.model.constants.SchemaConstants; import org.apache.directory.api.ldap.model.entry.DefaultEntry; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.ldif.LdifEntry; import org.apache.directory.api.ldap.model.ldif.LdifReader; import org.apache.directory.api.ldap.model.schema.SchemaManager; import org.apache.directory.api.ldap.schema.extractor.impl.DefaultSchemaLdifExtractor; import org.apache.directory.api.ldap.schema.extractor.impl.ResourceMap; import org.apache.directory.server.core.api.interceptor.context.AddOperationContext; import org.apache.directory.server.core.api.partition.PartitionTxn; import org.apache.directory.server.core.partition.ldif.AbstractLdifPartition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * In-memory schema-only partition which loads the data in the similar way as the * {@link org.apache.directory.api.ldap.schemaloader.JarLdifSchemaLoader}. * * @author Josef Cacek */ public class InMemorySchemaPartition extends AbstractLdifPartition { private static Logger LOG = LoggerFactory.getLogger(InMemorySchemaPartition.class); /** * Filesystem path separator pattern, either forward slash or backslash. java.util.regex.Pattern is immutable so only one * instance is needed for all uses. */ public InMemorySchemaPartition(SchemaManager schemaManager) { super(schemaManager); } /** * Partition initialization - loads schema entries from the files on classpath. * * @see org.apache.directory.server.core.partition.impl.avl.AvlPartition#doInit() */ @Override protected void doInit() throws LdapException { if (initialized) return; LOG.debug("Initializing schema partition " + getId()); super.doInit(); try { // load schema final Map<String, Boolean> resMap = ResourceMap.getResources(Pattern.compile("schema[/\\Q\\\\E]ou=schema.*")); for (String resourcePath : new TreeSet<String>(resMap.keySet())) { if (resourcePath.endsWith(".ldif")) { URL resource = DefaultSchemaLdifExtractor.getUniqueResource(resourcePath, "Schema LDIF file"); LdifReader reader = new LdifReader(resource.openStream()); LdifEntry ldifEntry = reader.next(); reader.close(); Entry entry = new DefaultEntry(schemaManager, ldifEntry.getEntry()); // add mandatory attributes if (entry.get(SchemaConstants.ENTRY_CSN_AT) == null) { entry.add(SchemaConstants.ENTRY_CSN_AT, defaultCSNFactory.newInstance().toString()); } if (entry.get(SchemaConstants.ENTRY_UUID_AT) == null) { entry.add(SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString()); } AddOperationContext addContext = new AddOperationContext(null, entry); try (PartitionTxn partitionTxn = this.beginWriteTransaction()) { addContext.setPartition(this); addContext.setTransaction(partitionTxn); super.add(addContext); } } } } catch (IOException e) { throw new LdapException(e); } } }
4,750
42.190909
125
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/web/sso/SSOTestBase.java
/* * JBoss, a division of Red Hat * Copyright 2006, Red Hat Middleware, LLC, and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.web.sso; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE; import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode; import static org.junit.Assert.assertTrue; import java.io.IOException; 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 java.util.concurrent.Callable; import java.util.concurrent.TimeoutException; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.HttpClientUtils; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.OperationBuilder; import org.jboss.as.test.http.util.TestHttpClientUtils; import org.jboss.as.test.integration.web.sso.interfaces.StatelessSession; import org.jboss.as.test.shared.RetryTaskExecutor; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; /** * Base class for tests of web app single sign-on * * @author Brian Stansberry * @author lbarreiro@redhat.com */ public abstract class SSOTestBase { private static Logger log = Logger.getLogger(SSOTestBase.class); /** * Test single sign-on across two web apps using form based auth * * @throws Exception */ public static void executeFormAuthSingleSignOnTest(URL serverA, URL serverB, Logger log) throws Exception { URL warA1 = new URL(serverA, "/war1/"); URL warB2 = new URL(serverB, "/war2/"); // Start by accessing the secured index.html of war1 CookieStore store = new BasicCookieStore(); HttpClient httpclient = TestHttpClientUtils.promiscuousCookieHttpClientBuilder() .setDefaultCookieStore(store) .disableRedirectHandling() .build(); try { checkAccessDenied(httpclient, warA1 + "index.html"); log.debug("Saw JSESSIONID=" + getSessionIdValueFromState(store)); // Submit the login form executeFormLogin(httpclient, warA1); String ssoID = processSSOCookie(store, serverA.toString(), serverB.toString()); log.debug("Saw JSESSIONIDSSO=" + ssoID); // Now try getting the war2 index using the JSESSIONIDSSO cookie log.debug("Prepare /war2/index.html get"); checkAccessAllowed(httpclient, warB2 + "index.html"); // Access a secured servlet that calls a secured Jakarta Enterprise Beans in war2 to test // propagation of the SSO identity to the Jakarta Enterprise Beans container. checkAccessAllowed(httpclient, warB2 + "EJBServlet"); // Now try logging out of war2 executeLogout(httpclient, warB2); } finally { HttpClientUtils.closeQuietly(httpclient); } try { // Reset Http client httpclient = HttpClients.createDefault(); // Try accessing war1 again checkAccessDenied(httpclient, warA1 + "index.html"); // Try accessing war2 again checkAccessDenied(httpclient, warB2 + "index.html"); } finally { HttpClientUtils.closeQuietly(httpclient); } } public static void executeNoAuthSingleSignOnTest(URL serverA, URL serverB, Logger log) throws Exception { URL warA1 = new URL(serverA, "/war1/"); URL warB2 = new URL(serverB + "/war2/"); URL warB6 = new URL(serverB + "/war6/"); // Start by accessing the secured index.html of war1 CookieStore store = new BasicCookieStore(); HttpClient httpclient = TestHttpClientUtils.promiscuousCookieHttpClientBuilder().setDefaultCookieStore(store).build(); try { checkAccessDenied(httpclient, warA1 + "index.html"); log.debug("Saw JSESSIONID=" + getSessionIdValueFromState(store)); // Submit the login form executeFormLogin(httpclient, warA1); String ssoID = processSSOCookie(store, serverA.toString(), serverB.toString()); log.debug("Saw JSESSIONIDSSO=" + ssoID); // Now try getting the war2 index using the JSESSIONIDSSO cookie log.debug("Prepare /war2/index.html get"); checkAccessAllowed(httpclient, warB2 + "index.html"); // Access a secured servlet that calls a secured Jakarta Enterprise Beans in war2 to test // propagation of the SSO identity to the Jakarta Enterprise Beans container. checkAccessAllowed(httpclient, warB2 + "EJBServlet"); // Do the same test on war6 to test SSO auth replication with no auth // configured war checkAccessAllowed(httpclient, warB6 + "index.html"); checkAccessAllowed(httpclient, warB2 + "EJBServlet"); } finally { HttpClientUtils.closeQuietly(httpclient); } } /** * Test single sign-on across two web apps using form based auth. * * Test that after session timeout SSO is destroyed. * * @throws Exception */ public static void executeFormAuthSSOTimeoutTest(URL serverA, URL serverB, Logger log) throws Exception { URL warA1 = new URL(serverA, "/war1/"); URL warB2 = new URL(serverB, "/war2/"); // Start by accessing the secured index.html of war1 CookieStore store = new BasicCookieStore(); HttpClient httpclient = TestHttpClientUtils.promiscuousCookieHttpClientBuilder() .setDefaultCookieStore(store) .disableRedirectHandling() .build(); try { checkAccessDenied(httpclient, warA1 + "index.html"); log.debug("Saw JSESSIONID=" + getSessionIdValueFromState(store)); // Submit the login form executeFormLogin(httpclient, warA1); String ssoID = processSSOCookie(store, serverA.toString(), serverB.toString()); log.debug("Saw JSESSIONIDSSO=" + ssoID); // After login I should still have access + set session timeout to 5 seconds checkAccessAllowed(httpclient, warA1 + "set_session_timeout.jsp"); // Also access to war2 should be granted + set session timeout to 5 seconds checkAccessAllowed(httpclient, warB2 + "set_session_timeout.jsp"); // wait 5 seconds session timeout + 1 seconds reserve Thread.sleep((5+1)*1000); // After timeout I should be not able to access the app checkAccessDenied(httpclient, warA1 + "index.html"); checkAccessDenied(httpclient, warB2 + "index.html"); } finally { HttpClientUtils.closeQuietly(httpclient); } } public static void executeLogout(HttpClient httpConn, URL warURL) throws IOException { HttpGet logout = new HttpGet(warURL + "Logout"); HttpResponse response = httpConn.execute(logout); try { int statusCode = response.getStatusLine().getStatusCode(); assertTrue("Logout: Didn't see code 302 (HTTP_MOVED_TEMP), but saw instead " + statusCode, statusCode == HttpURLConnection.HTTP_MOVED_TEMP); Header location = response.getFirstHeader("Location"); assertTrue("Get of " + warURL + "Logout not redirected to login page", location.getValue().contains("index.html")); } finally { HttpClientUtils.closeQuietly(response); } } public static void checkAccessAllowed(HttpClient httpConn, String url) throws IOException { HttpGet getMethod = new HttpGet(url); HttpResponse response = httpConn.execute(getMethod); try { int statusCode = response.getStatusLine().getStatusCode(); assertTrue("Expected code == OK but got " + statusCode + " for request=" + url, statusCode == HttpURLConnection.HTTP_OK); String body = EntityUtils.toString(response.getEntity()); assertTrue("Get of " + url + " redirected to login page", !body.contains("j_security_check")); } finally { HttpClientUtils.closeQuietly(response); } } public static void executeFormLogin(HttpClient httpConn, URL warURL) throws IOException { // Submit the login form HttpPost formPost = new HttpPost(warURL + "j_security_check"); formPost.addHeader("Referer", warURL + "login.html"); List<NameValuePair> formparams = new ArrayList<>(); formparams.add(new BasicNameValuePair("j_username", "user1")); formparams.add(new BasicNameValuePair("j_password", "password1")); formPost.setEntity(new UrlEncodedFormEntity(formparams, StandardCharsets.UTF_8)); HttpResponse postResponse = httpConn.execute(formPost); try { int statusCode = postResponse.getStatusLine().getStatusCode(); Header[] 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 index.html page String indexURL = postResponse.getFirstHeader("Location").getValue(); HttpGet rediretGet = new HttpGet(indexURL); HttpResponse redirectResponse = httpConn.execute(rediretGet); statusCode = redirectResponse.getStatusLine().getStatusCode(); errorHeaders = redirectResponse.getHeaders("X-NoJException"); assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK); assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0); String body = EntityUtils.toString(redirectResponse.getEntity()); assertTrue("Get of " + indexURL + " redirected to login page", !body.contains("j_security_check")); } finally { HttpClientUtils.closeQuietly(postResponse); } } public static void checkAccessDenied(HttpClient httpConn, String url) throws IOException { HttpGet getMethod = new HttpGet(url); HttpResponse response = httpConn.execute(getMethod); try { int statusCode = response.getStatusLine().getStatusCode(); assertTrue("Expected code == OK but got " + statusCode + " for request=" + url, statusCode == HttpURLConnection.HTTP_OK); String body = EntityUtils.toString(response.getEntity()); assertTrue("Redirected to login page for request=" + url + ", body[" + body + "]", body.indexOf("j_security_check") > 0); } finally { HttpClientUtils.closeQuietly(response); } } public static String processSSOCookie(CookieStore cookieStore, String serverA, String serverB) { String ssoID = null; for (Cookie cookie : cookieStore.getCookies()) { if ("JSESSIONIDSSO".equalsIgnoreCase(cookie.getName())) { ssoID = cookie.getValue(); if (!serverA.equals(serverB)) { // Make an sso cookie to send to serverB Cookie copy = copyCookie(cookie, serverB); cookieStore.addCookie(copy); } } } assertTrue("Didn't see JSESSIONIDSSO: " + cookieStore.getCookies(), ssoID != null); return ssoID; } public static Cookie copyCookie(Cookie toCopy, String targetServer) { // Parse the target server down to a domain name int index = targetServer.indexOf("://"); if (index > -1) { targetServer = targetServer.substring(index + 3); } // JBAS-8540 // need to be able to parse IPv6 URLs which have enclosing brackets // HttpClient 3.1 creates cookies which include the square brackets // index = targetServer.indexOf(":"); index = targetServer.lastIndexOf(":"); if (index > -1) { targetServer = targetServer.substring(0, index); } index = targetServer.indexOf("/"); if (index > -1) { targetServer = targetServer.substring(0, index); } // Cookie copy = new Cookie(targetServer, toCopy.getName(), toCopy.getValue(), "/", null, false); BasicClientCookie copy = new BasicClientCookie(toCopy.getName(), toCopy.getValue()); copy.setDomain(targetServer); return copy; } public static String getSessionIdValueFromState(CookieStore cookieStore) { String sessionID = null; for (Cookie cookie : cookieStore.getCookies()) { if ("JSESSIONID".equalsIgnoreCase(cookie.getName())) { sessionID = cookie.getValue(); break; } } return sessionID; } public static WebArchive createSsoWar(String warName) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); String resourcesLocation = "org/jboss/as/test/integration/web/sso/resources/"; WebArchive war = ShrinkWrap.create(WebArchive.class, warName); war.setWebXML(tccl.getResource(resourcesLocation + "web-form-auth.xml")); war.addAsWebInfResource(tccl.getResource(resourcesLocation + "jboss-web.xml"), "jboss-web.xml"); war.addAsWebResource(tccl.getResource(resourcesLocation + "error.html"), "error.html"); war.addAsWebResource(tccl.getResource(resourcesLocation + "index.html"), "index.html"); war.addAsWebResource(tccl.getResource(resourcesLocation + "index.jsp"), "index.jsp"); war.addAsWebResource(tccl.getResource(resourcesLocation + "set_session_timeout.jsp"), "set_session_timeout.jsp"); war.addAsWebResource(tccl.getResource(resourcesLocation + "login.html"), "login.html"); war.addClass(EJBServlet.class); war.addClass(LogoutServlet.class); return war; } public static EnterpriseArchive createSsoEar() { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); String resourcesLocation = "org/jboss/as/test/integration/web/sso/resources/"; WebArchive war1 = createSsoWar("sso-form-auth1.war"); WebArchive war2 = createSsoWar("sso-form-auth2.war"); WebArchive war3 = createSsoWar("sso-with-no-auth.war"); // Remove jboss-web.xml so the war will not have an authenticator war3.delete(war3.get("WEB-INF/jboss-web.xml").getPath()); JavaArchive webEjbs = ShrinkWrap.create(JavaArchive.class, "jbosstest-web-ejbs.jar"); webEjbs.addAsManifestResource(tccl.getResource(resourcesLocation + "ejb-jar.xml"), "ejb-jar.xml"); webEjbs.addAsManifestResource(tccl.getResource(resourcesLocation + "jboss.xml"), "jboss.xml"); webEjbs.addPackage(StatelessSession.class.getPackage()); EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "web-sso.ear"); ear.setApplicationXML(tccl.getResource(resourcesLocation + "application.xml")); ear.addAsModule(war1); ear.addAsModule(war2); ear.addAsModule(war3); ear.addAsModule(webEjbs); return ear; } public static void addSso(ModelControllerClient client) throws Exception { final List<ModelNode> updates = new ArrayList<>(); // SSO element name must be 'configuration' updates.add(createOpNode("subsystem=undertow/server=default-server/host=default-host/setting=single-sign-on", ADD)); applyUpdates(updates, client); } public static void removeSso(final ModelControllerClient client) throws Exception { final List<ModelNode> updates = new ArrayList<>(); updates.add(createOpNode("subsystem=undertow/server=default-server/host=default-host/setting=single-sign-on", REMOVE)); applyUpdates(updates, client); } public 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")); } } } // Reload operation is not handled well by Arquillian // See ARQ-791: JMX: Arquillian is unable to reconnect to JMX server if the connection is lost public static void restartServer(final ModelControllerClient client) { try { applyUpdates(Arrays.asList(createOpNode(null, "reload")), client); } catch (Exception e) { throw new RuntimeException("Restart operation not successful. " + e.getMessage()); } try { RetryTaskExecutor<Boolean> rte = new RetryTaskExecutor<>(); rte.retryTask(new Callable<Boolean>() { public Boolean call() throws Exception { ModelNode readOp = createOpNode(null, READ_ATTRIBUTE_OPERATION); readOp.get("name").set("server-state"); ModelNode result = client.execute(new OperationBuilder(readOp).build()); if (result.hasDefined("outcome") && "success".equals(result.get("outcome").asString())) { if ((result.hasDefined("result")) && (result.get("result").asString().equals("running"))) return true; } log.trace("Server is down."); throw new Exception("Connector not available."); } }); } catch (TimeoutException e) { throw new RuntimeException("Timeout on restart operation. " + e.getMessage()); } log.trace("Server is up."); } }
20,451
44.048458
152
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/web/sso/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.sso; import java.io.IOException; 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 = 2133162198049851268L; @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException { HttpSession session = request.getSession(false); if (session != null) { session.invalidate(); } response.sendRedirect(request.getContextPath() + "/index.html"); } }
1,905
37.12
105
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/web/sso/EJBServlet.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.sso; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * A servlet that accesses an Jakarta Enterprise Beans and tests whether the call argument is * serialized. * * @author Scott.Stark@jboss.org * @author */ public class EJBServlet extends HttpServlet { private static final long serialVersionUID = 2070931818661985879L; @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException { /* try { InitialContext ctx = new InitialContext(); Context enc = (Context) ctx.lookup("java:comp/env"); StatelessSessionHome home = (StatelessSessionHome) enc.lookup("ejb/OptimizedEJB"); StatelessSession bean = home.create(); bean.noop(); Object homeRef = enc.lookup("ejb/OptimizedEJB"); home = (StatelessSessionHome) PortableRemoteObject.narrow(homeRef, StatelessSessionHome.class); bean = home.create(); bean.noop(); bean.getData(); StatelessSessionLocalHome localHome = (StatelessSessionLocalHome) enc.lookup("ejb/local/OptimizedEJB"); StatelessSessionLocal localBean = localHome.create(); localBean.noop(); } catch (Exception e) { throw new ServletException("Failed to call OptimizedEJB through remote and local interfaces", e); } */ response.setContentType("text/html"); try (PrintWriter out = response.getWriter()) { out.println("<html>"); out.println("<head><title>EJBServlet</title></head>"); out.println("<body>Tests passed<br>Time:" + new Date().toString() + "</body>"); out.println("</html>"); } } }
2,984
38.8
115
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/web/sso/interfaces/StatelessSession.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.sso.interfaces; import java.rmi.RemoteException; import jakarta.ejb.EJBObject; /** * A trivial SessionBean interface. * * @author Scott.Stark@jboss.org */ public interface StatelessSession extends EJBObject { /** A method that returns its arg */ String echo(String arg) throws RemoteException; /** * A method that does nothing. It is used to test call optimization. */ void noop() throws RemoteException; /** Return a data object */ ReturnData getData() throws RemoteException; }
1,599
33.042553
72
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/web/sso/interfaces/StatelessSessionLocal.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.sso.interfaces; import java.rmi.RemoteException; import jakarta.ejb.EJBLocalObject; /** * A trivial SessionBean local interface. * * @author Scott.Stark@jboss.org */ public interface StatelessSessionLocal extends EJBLocalObject { /** A method that returns its arg */ String echo(String arg) throws RemoteException; /** A method that does nothing. It is used to test call optimization. */ void noop(); }
1,503
34.809524
76
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/web/sso/interfaces/StatelessSessionBean.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.sso.interfaces; import java.security.Principal; import jakarta.ejb.CreateException; import jakarta.ejb.SessionBean; import jakarta.ejb.SessionContext; import org.jboss.logging.Logger; /** * A simple session bean for testing declarative security. * * @author Scott.Stark@jboss.org */ public class StatelessSessionBean implements SessionBean { private static final long serialVersionUID = -4565135285688543978L; static Logger log = Logger.getLogger(StatelessSessionBean.class); private SessionContext sessionContext; public void ejbCreate() throws CreateException { log.debug("ejbCreate() called"); } public void ejbActivate() { log.debug("ejbActivate() called"); } public void ejbPassivate() { log.debug("ejbPassivate() called"); } public void ejbRemove() { log.debug("ejbRemove() called"); } public void setSessionContext(SessionContext context) { log.debug("setSessionContext() called"); sessionContext = context; } public String echo(String arg) { log.debug("echo, arg=" + arg); Principal p = sessionContext.getCallerPrincipal(); log.debug("echo, callerPrincipal=" + p); return p.getName(); } public void noop() { log.debug("noop"); } public ReturnData getData() { ReturnData data = new ReturnData(); data.data = "TheReturnData"; return data; } }
2,531
29.142857
71
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/web/sso/interfaces/StatelessSessionHome.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.sso.interfaces; import java.rmi.RemoteException; import jakarta.ejb.CreateException; import jakarta.ejb.EJBHome; public interface StatelessSessionHome extends EJBHome { StatelessSession create() throws RemoteException, CreateException; }
1,319
40.25
70
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/web/sso/interfaces/ReturnData.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.sso.interfaces; import java.io.Serializable; /** * A class that is placed into the WEB-INF/classes directory that accesses a * class loaded from a jar jbosstest-web.ear/lib due to a reference from the * jbosstest-web-ejbs.jar manifest ClassPath. * * @author Scott.Stark@jboss.org */ public class ReturnData implements Serializable { private static final long serialVersionUID = -6620950977249481726L; public String data; }
1,515
37.871795
76
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/web/sso/interfaces/StatelessSessionLocalHome.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.sso.interfaces; import jakarta.ejb.CreateException; import jakarta.ejb.EJBLocalHome; /** * A trivial local SessionBean home interface. * * @author Scott.Stark@jboss.org */ public interface StatelessSessionLocalHome extends EJBLocalHome { StatelessSessionLocal create() throws CreateException; }
1,379
38.428571
70
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/domain/management/util/JBossAsManagedConfiguration.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.domain.management.util; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import javax.security.auth.callback.CallbackHandler; import org.jboss.arquillian.container.spi.ConfigurationException; import org.jboss.arquillian.container.spi.client.deployment.Validate; import org.jboss.as.arquillian.container.CommonContainerConfiguration; import org.jboss.as.test.shared.TimeoutUtil; /** * JBossAsManagedConfiguration * * @author Brian Stansberry */ public class JBossAsManagedConfiguration extends CommonContainerConfiguration { public static JBossAsManagedConfiguration createFromClassLoaderResources(String domainConfigPath, String hostConfigPath) { JBossAsManagedConfiguration result = new JBossAsManagedConfiguration(); if (domainConfigPath != null) { result.setDomainConfigFile(loadConfigFileFromContextClassLoader(domainConfigPath)); } if (hostConfigPath != null) { result.setHostConfigFile(hostConfigPath); } return result; } public static String loadConfigFileFromContextClassLoader(String resourcePath) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); URL url = tccl.getResource(resourcePath); assert url != null : "cannot find resource at path " + resourcePath; return new File(toURI(url)).getAbsolutePath(); } private static URI toURI(URL url) { try { return url.toURI(); } catch (URISyntaxException e) { throw new RuntimeException(e); } } private String jbossHome = System.getProperty("jboss.home"); private String javaHome = System.getenv("JAVA_HOME"); private String controllerJavaHome = System.getenv("JAVA_HOME"); private String modulePath = System.getProperty("module.path"); private String javaVmArguments = System.getProperty("server.jvm.args", "-Xmx512m"); private int startupTimeoutInSeconds = TimeoutUtil.adjust(120); private boolean outputToConsole = true; private String hostControllerManagementProtocol = "remote"; private String hostControllerManagementAddress = System.getProperty("jboss.test.host.primary.address", "localhost"); private int hostControllerManagementPort = 9999; private String hostName = "primary"; private String domainDir; private String domainConfigFile; private String hostConfigFile; private String hostCommandLineProperties; private boolean adminOnly; private boolean readOnlyDomain; private boolean readOnlyHost; private CallbackHandler callbackHandler = Authentication.getCallbackHandler(); private String mgmtUsersFile; private String mgmtGroupsFile; private boolean backupDC; private boolean cachedDC; public JBossAsManagedConfiguration(String jbossHome) { if (jbossHome != null) { this.jbossHome = jbossHome; this.modulePath = new File(jbossHome, "modules").getAbsolutePath(); } } public JBossAsManagedConfiguration() { } /* * (non-Javadoc) * * @see org.jboss.as.arquillian.container.JBossAsContainerConfiguration#validate() */ @Override public void validate() throws ConfigurationException { super.validate(); Validate.configurationDirectoryExists(jbossHome, "jbossHome must exist at " + jbossHome); if (javaHome != null) { Validate.configurationDirectoryExists(javaHome, "javaHome must exist at " + javaHome); } if (controllerJavaHome != null) { Validate.configurationDirectoryExists(controllerJavaHome, "controllerJavaHome must exist at " + controllerJavaHome); } } /** * @return the jbossHome */ public String getJbossHome() { return jbossHome; } /** * @param jbossHome the jbossHome to set */ public void setJbossHome(String jbossHome) { this.jbossHome = jbossHome; } /** * @return the javaHome */ public String getJavaHome() { return javaHome; } /** * @param javaHome the javaHome to set */ public void setJavaHome(String javaHome) { this.javaHome = javaHome; } /** * @return the controllerJavaHome */ public String getControllerJavaHome() { return controllerJavaHome; } /** * @param controllerJavaHome the javaHome to set */ public void setControllerJavaHome(String controllerJavaHome) { this.controllerJavaHome = controllerJavaHome; } /** * @return the javaVmArguments */ public String getJavaVmArguments() { return javaVmArguments; } /** * @param javaVmArguments the javaVmArguments to set */ public void setJavaVmArguments(String javaVmArguments) { this.javaVmArguments = javaVmArguments; } /** * @param startupTimeoutInSeconds the startupTimeoutInSeconds to set */ public void setStartupTimeoutInSeconds(int startupTimeoutInSeconds) { this.startupTimeoutInSeconds = startupTimeoutInSeconds; } /** * @return the startupTimeoutInSeconds */ public int getStartupTimeoutInSeconds() { return startupTimeoutInSeconds; } /** * @param outputToConsole the outputToConsole to set */ public void setOutputToConsole(boolean outputToConsole) { this.outputToConsole = outputToConsole; } /** * @return the outputToConsole */ public boolean isOutputToConsole() { return outputToConsole; } public String getHostControllerManagementProtocol() { return hostControllerManagementProtocol; } public void setHostControllerManagementProtocol(String hostControllerManagementProtocol) { this.hostControllerManagementProtocol = hostControllerManagementProtocol; } public String getHostControllerManagementAddress() { return hostControllerManagementAddress; } public void setHostControllerManagementAddress(String hostControllerManagementAddress) { this.hostControllerManagementAddress = hostControllerManagementAddress; } public int getHostControllerManagementPort() { return hostControllerManagementPort; } public void setHostControllerManagementPort(int hostControllerManagementPort) { this.hostControllerManagementPort = hostControllerManagementPort; } public String getDomainDirectory() { return domainDir; } public void setDomainDirectory(String domainDir) { this.domainDir = domainDir; } public String getDomainConfigFile() { return domainConfigFile; } public void setDomainConfigFile(String domainConfigFile) { this.domainConfigFile = domainConfigFile; } public String getHostConfigFile() { return hostConfigFile; } public void setHostConfigFile(String hostConfigFile) { this.hostConfigFile = hostConfigFile; } public String getMgmtUsersFile() { return mgmtUsersFile; } public void setMgmtUsersFile(String mgmtUsersFile) { this.mgmtUsersFile = mgmtUsersFile; } public String getMgmtGroupsFile() { return mgmtGroupsFile; } public void setMgmtGroupsFile(String mgmtGroupsFile) { this.mgmtGroupsFile = mgmtGroupsFile; } public String getHostCommandLineProperties() { return hostCommandLineProperties; } public void setHostCommandLineProperties(String hostCommandLineProperties) { this.hostCommandLineProperties = hostCommandLineProperties; } public void addHostCommandLineProperty(String hostCommandLineProperty) { this.hostCommandLineProperties = this.hostCommandLineProperties == null ? hostCommandLineProperty : this.hostCommandLineProperties + " " + hostCommandLineProperty; } public String getHostName() { return hostName; } public void setHostName(String hostName) { this.hostName = hostName; } public String getModulePath() { return modulePath; } public void setModulePath(final String modulePath) { this.modulePath = modulePath; } public boolean isAdminOnly() { return adminOnly; } public void setAdminOnly(boolean adminOnly) { this.adminOnly = adminOnly; } public boolean isReadOnlyDomain() { return readOnlyDomain; } public void setReadOnlyDomain(boolean readOnlyDomain) { this.readOnlyDomain = readOnlyDomain; } public boolean isReadOnlyHost() { return readOnlyHost; } public void setReadOnlyHost(boolean readOnlyHost) { this.readOnlyHost = readOnlyHost; } public CallbackHandler getCallbackHandler() { return callbackHandler; } public void setCallbackHandler(CallbackHandler callbackHandler) { this.callbackHandler = callbackHandler; } public boolean isBackupDC() { return backupDC; } public void setBackupDC(boolean backupDC) { this.backupDC = backupDC; } public boolean isCachedDC() { return cachedDC; } public void setCachedDC(boolean cachedDC) { this.cachedDC = cachedDC; } }
10,513
27.493225
128
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/jms/auxiliary/CreateTopicSetupTask.java
package org.jboss.as.test.jms.auxiliary; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; /** * Author: jmartisk * Date: 2/27/12 * Time: 9:06 AM */ public class CreateTopicSetupTask implements ServerSetupTask { public static final String TOPIC_NAME = "myAwesomeTopic"; public static final String TOPIC_JNDI_NAME = "topic/myAwesomeTopic"; private JMSOperations adminOperations; @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { adminOperations = JMSOperationsProvider.getInstance(managementClient); adminOperations.createJmsTopic(TOPIC_NAME, TOPIC_JNDI_NAME); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { if (adminOperations != null) { adminOperations.removeJmsTopic(TOPIC_NAME); adminOperations.close(); } } }
1,122
32.029412
98
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/jms/auxiliary/CreateQueueSetupTask.java
package org.jboss.as.test.jms.auxiliary; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; /** * Author: jmartisk * Date: 2/27/12 * Time: 9:06 AM */ public class CreateQueueSetupTask implements ServerSetupTask { public static final String QUEUE1_NAME = "myAwesomeQueue"; public static final String QUEUE1_JNDI_NAME = "queue/myAwesomeQueue"; public static final String QUEUE2_NAME = "myAwesomeQueue2"; public static final String QUEUE2_JNDI_NAME = "queue/myAwesomeQueue2"; public static final String QUEUE3_NAME = "myAwesomeQueue3"; public static final String QUEUE3_JNDI_NAME = "queue/myAwesomeQueue3"; private JMSOperations adminOperations; @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { adminOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); adminOperations.createJmsQueue(QUEUE1_NAME, QUEUE1_JNDI_NAME); adminOperations.createJmsQueue(QUEUE2_NAME, QUEUE2_JNDI_NAME); adminOperations.createJmsQueue(QUEUE3_NAME, QUEUE3_JNDI_NAME); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { if (adminOperations != null) { adminOperations.removeJmsQueue(QUEUE1_NAME); adminOperations.removeJmsQueue(QUEUE2_NAME); adminOperations.removeJmsQueue(QUEUE3_NAME); adminOperations.close(); } } }
1,685
37.318182
100
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/http/util/TestHttpClientUtils.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.http.util; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.utils.DateUtils; import org.apache.http.client.utils.HttpClientUtils; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.cookie.Cookie; import org.apache.http.cookie.CookieOrigin; import org.apache.http.cookie.CookieSpec; import org.apache.http.cookie.CookieSpecProvider; import org.apache.http.cookie.MalformedCookieException; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CookieSpecRegistries; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.impl.cookie.BasicDomainHandler; import org.apache.http.impl.cookie.BasicExpiresHandler; import org.apache.http.impl.cookie.BasicMaxAgeHandler; import org.apache.http.impl.cookie.BasicPathHandler; import org.apache.http.impl.cookie.BasicSecureHandler; import org.apache.http.impl.cookie.RFC6265CookieSpec; import org.apache.http.protocol.HttpContext; /** * Utility class with http/https utilities. Not to be confused with Apache {@link HttpClientUtils}. * * @author Dominik Pospisil <dpospisi@redhat.com> * @author <a href="mailto:pskopek@redhat.com">Peter Skopek</a> * @author Stuart Douglas * @author Radoslav Husar * @version August 2015 */ public class TestHttpClientUtils { /** *@param credentialsProvider optional cred provider * @return client that doesn't verify https connections */ public static CloseableHttpClient getHttpsClient(CredentialsProvider credentialsProvider) { try { SSLContext ctx = getSslContext(); SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(ctx, new NoopHostnameVerifier()); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslConnectionFactory) .build(); HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry); HttpClientBuilder builder = HttpClientBuilder.create() .setSSLSocketFactory(sslConnectionFactory) .setSSLHostnameVerifier(new NoopHostnameVerifier()) .setConnectionManager(ccm); if (credentialsProvider != null) { builder.setDefaultCredentialsProvider(credentialsProvider); } return builder.build(); } catch (Exception ex) { ex.printStackTrace(); return null; } } public static SSLContext getSslContext() throws NoSuchAlgorithmException, KeyManagementException { SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[]{tm}, null); ctx.init(null, new TrustManager[]{tm}, null); return ctx; } /** * Creates a http client that sends cookies to every domain, not just the originating domain. * As we don't actually have a load balancer for the clustering tests, we use this instead. * * @return {@link CloseableHttpClient} that gives free cookies to everybody * @see TestHttpClientUtils#promiscuousCookieHttpClientBuilder() * @see <a href="http://tools.ietf.org/html/rfc6265">RFC6265 - HTTP State Management Mechanism</a> */ public static CloseableHttpClient promiscuousCookieHttpClient() { return promiscuousCookieHttpClientBuilder().build(); } /** * Same as {@link TestHttpClientUtils#promiscuousCookieHttpClient()} but instead returns a builder that can be further configured. * * @return {@link HttpClientBuilder} of the http client that gives free cookies to everybody * @see TestHttpClientUtils#promiscuousCookieHttpClient() */ public static HttpClientBuilder promiscuousCookieHttpClientBuilder() { HttpClientBuilder builder = HttpClients.custom(); RegistryBuilder<CookieSpecProvider> registryBuilder = CookieSpecRegistries.createDefaultBuilder(); Registry<CookieSpecProvider> promiscuousCookieSpecRegistry = registryBuilder.register("promiscuous", new PromiscuousCookieSpecProvider()).build(); builder.setDefaultCookieSpecRegistry(promiscuousCookieSpecRegistry); RequestConfig requestConfig = RequestConfig.custom().setCookieSpec("promiscuous").build(); builder.setDefaultRequestConfig(requestConfig); builder.setDefaultCookieStore(new PromiscuousCookieStore()); return builder; } private static class PromiscuousCookieSpecProvider implements CookieSpecProvider { @Override public CookieSpec create(HttpContext context) { return new PromiscuousCookieSpec(); } } private static class PromiscuousCookieSpec extends RFC6265CookieSpec { private PromiscuousCookieSpec() { super( new BasicPathHandler(), new BasicDomainHandler() { @Override public boolean match(Cookie cookie, CookieOrigin origin) { return true; } @Override public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException { // Accept any } }, new BasicMaxAgeHandler(), new BasicSecureHandler(), new BasicExpiresHandler(new String[] { DateUtils.PATTERN_RFC1123, DateUtils.PATTERN_RFC1036, DateUtils.PATTERN_ASCTIME }) ); } } private static class PromiscuousCookieStore extends BasicCookieStore { @Override public synchronized void addCookie(Cookie cookie) { ((BasicClientCookie) cookie).setDomain(null); super.addCookie(cookie); } } }
8,336
41.535714
154
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/SecureExpressionUtil.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.security.common; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.asset.StringAsset; public final class SecureExpressionUtil { public static final class SecureExpressionData extends org.jboss.as.test.shared.SecureExpressionUtil.SecureExpressionData { private final String property; public SecureExpressionData(String clearText, String property) { super(clearText); this.property = property; } } public static void setupCredentialStoreExpressions(String storeName, SecureExpressionData... toConfigure) throws Exception { org.jboss.as.test.shared.SecureExpressionUtil.setupCredentialStoreExpressions(storeName, toConfigure); } public static void setupCredentialStore(ManagementClient arquillianClient, String storeName, String storeLocation) throws Exception { org.wildfly.core.testrunner.ManagementClient client = getCoreManagmentClient(arquillianClient); org.jboss.as.test.shared.SecureExpressionUtil.setupCredentialStore(client, storeName, storeLocation); } public static void teardownCredentialStore(ManagementClient arquillianClient, String storeName, String storeLocation) throws Exception { org.wildfly.core.testrunner.ManagementClient client = getCoreManagmentClient(arquillianClient); org.jboss.as.test.shared.SecureExpressionUtil.teardownCredentialStore(client, storeName, storeLocation); } public static Asset getDeploymentPropertiesAsset(SecureExpressionData... expressions) { StringBuilder builder = new StringBuilder("# Conversion of well known static properties to dynamic secure " + "expressions calculated by " + SecureExpressionUtil.class.getSimpleName() + " during test setup\n"); if (expressions != null) { for (SecureExpressionData expressionData : expressions) { if (expressionData.property != null && !expressionData.property.isEmpty()) { builder.append(expressionData.property); builder.append('='); builder.append(expressionData.getExpression()); builder.append('\n'); } } } return new StringAsset(builder.toString()); } public static Class[] getDeploymentClasses() { return new Class[] { SecureExpressionUtil.class, SecureExpressionData.class, org.jboss.as.test.shared.SecureExpressionUtil.class, org.jboss.as.test.shared.SecureExpressionUtil.SecureExpressionData.class }; } private static org.wildfly.core.testrunner.ManagementClient getCoreManagmentClient(ManagementClient arquillianClient) { return new org.wildfly.core.testrunner.ManagementClient(arquillianClient.getControllerClient(), arquillianClient.getMgmtAddress(), arquillianClient.getMgmtPort(), arquillianClient.getMgmtProtocol()); } }
3,809
46.625
207
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/AbstractElytronSetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common; import java.util.Arrays; import java.util.ListIterator; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.shared.ServerReload; import org.jboss.logging.Logger; import org.wildfly.test.security.common.elytron.ConfigurableElement; /** * Abstract parent for server setup tasks configuring Elytron. Implementing classes overrides {@link #getConfigurableElements()} * method to provide configured on which this task will call {@link ConfigurableElement#create(CLIWrapper)}. * * @author Josef Cacek */ public abstract class AbstractElytronSetupTask implements org.jboss.as.arquillian.api.ServerSetupTask { private static final Logger LOGGER = Logger.getLogger(AbstractElytronSetupTask.class); private ConfigurableElement[] configurableElements; private ManagementClient cachedManagementClient; @Override public void setup(final ManagementClient managementClient, final String containerId) throws Exception { // WFLY-12514. The overridable setup(ModelControllerClient) method used ServerReload.reloadIfRequired(ModelControllerClient) // but it's more robust to use ServerReload.reloadIfRequired(ManagementClient). To let it do that // without breaking compatibility, cache the ManagementClient this.cachedManagementClient = managementClient; setup(managementClient.getControllerClient()); this.cachedManagementClient = null; } @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception { // WFLY-12514. The overridable setup(ModelControllerClient) method used ServerReload.reloadIfRequired(ModelControllerClient) // but it's more robust to use ServerReload.reloadIfRequired(ManagementClient). To let it do that // without breaking compatibility, cache the ManagementClient this.cachedManagementClient = managementClient; tearDown(managementClient.getControllerClient()); this.cachedManagementClient = null; } /** * Creates configuration elements (provided by implementation of {@link #getConfigurableElements()} method) and calls * {@link ConfigurableElement#create(CLIWrapper)} for them. */ protected void setup(final ModelControllerClient modelControllerClient) throws Exception { configurableElements = getConfigurableElements(); if (configurableElements == null || configurableElements.length == 0) { LOGGER.warn("Empty Elytron configuration."); return; } try (CLIWrapper cli = new CLIWrapper(true)) { for (final ConfigurableElement configurableElement : configurableElements) { LOGGER.infov("Adding element {0} ({1})", configurableElement.getName(), configurableElement.getClass().getSimpleName()); configurableElement.create(modelControllerClient, cli); } } reloadIfRequired(modelControllerClient); } /** * Reverts configuration changes done by {@link #setup(ModelControllerClient)} method - i.e. calls {@link ConfigurableElement#remove(CLIWrapper)} method * on instances provided by {@link #getConfigurableElements()} (in reverse order). */ protected void tearDown(ModelControllerClient modelControllerClient) throws Exception { if (configurableElements == null || configurableElements.length == 0) { LOGGER.warn("Empty Elytron configuration."); return; } try (CLIWrapper cli = new CLIWrapper(true)) { final ListIterator<ConfigurableElement> reverseConfigIt = Arrays.asList(configurableElements) .listIterator(configurableElements.length); while (reverseConfigIt.hasPrevious()) { final ConfigurableElement configurableElement = reverseConfigIt.previous(); LOGGER.infov("Removing element {0} ({1})", configurableElement.getName(), configurableElement.getClass().getSimpleName()); configurableElement.remove(modelControllerClient, cli); } } this.configurableElements = null; reloadIfRequired(modelControllerClient); } /** * Returns not-{@code null} array of configurations to be created by this server setup task. * * @return not-{@code null} array of instances to be created */ protected abstract ConfigurableElement[] getConfigurableElements(); private void reloadIfRequired(ModelControllerClient modelControllerClient) throws Exception { if (cachedManagementClient != null) { ServerReload.reloadIfRequired(cachedManagementClient); } else { // Some subclass must have overridden setup(ManagementClient, String) or tearDown(ManagementClient, String). // Probably ok; might hit WFLY-12514 type problems if the server isn't on the default address/port // in which case the fix is to correct the overriding code. //noinspection deprecation ServerReload.reloadIfRequired(modelControllerClient); } } }
6,404
44.425532
156
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/ModelNodeUtil.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common; import org.jboss.dmr.ModelNode; /** * Helper methods for {@link ModelNode} class. * * @author Josef Cacek */ public class ModelNodeUtil { /** * Set attribute of given node if the value is not-<code>null</code>. */ public static void setIfNotNull(ModelNode node, String attribute, String value) { if (value != null) { node.get(attribute).set(value); } } /** * Set attribute of given node if the value is not-<code>null</code>. */ public static void setIfNotNull(ModelNode node, String attribute, Boolean value) { if (value != null) { node.get(attribute).set(value); } } /** * Set attribute of given node if the value is not-<code>null</code>. */ public static void setIfNotNull(ModelNode node, String attribute, Integer value) { if (value != null) { node.get(attribute).set(value); } } /** * Set list attribute of given node if the value is not-<code>null</code>. */ public static void setIfNotNull(ModelNode node, String attribute, String... listValue) { if (listValue != null) { ModelNode listNode = node.get(attribute); for (String value : listValue) { listNode.add(value); } } } }
2,401
31.459459
92
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/ConstantPrincipalDecoder.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; /** * Elytron constant-principal-decoder configuration implementation. * * @author Ondrej Kotek */ public class ConstantPrincipalDecoder extends AbstractConstantHelper { private ConstantPrincipalDecoder(Builder builder) { super(builder); } @Override protected String getConstantElytronType() { return "constant-principal-decoder"; } /** * Creates builder. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder pattern for the class. */ public static final class Builder extends AbstractConstantHelper.Builder<Builder> { private Builder() { } public ConstantPrincipalDecoder build() { return new ConstantPrincipalDecoder(this); } @Override protected Builder self() { return this; } } }
1,999
27.985507
87
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SecurityDomain.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; /** * Marker interface representing Elytron Security domain configuration. * * @author Josef Cacek */ public interface SecurityDomain extends ConfigurableElement { }
1,246
36.787879
71
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/CustomPrincipalTransformer.java
/* * Copyright 2023 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.security.common.elytron; import static org.jboss.as.controller.PathElement.pathElement; import java.util.HashMap; import java.util.Map; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; import org.wildfly.test.security.common.ModelNodeUtil; /** * A {@link ConfigurableElement} to define a custom principal transformer. Requires a {@link Module} to be * added to the server. * * @author <a href="mailto:carodrig@redhat.com">Cameron Rodriguez</a> */ public class CustomPrincipalTransformer implements ConfigurableElement { private final PathAddress address; private final String name; private final String className; private final String module; private final Map<String, String> configuration; protected CustomPrincipalTransformer(String name, String className, String module, Map<String, String> configuration) { this.name = name; this.className = className; this.module = module; this.configuration = configuration; this.address = PathAddress.pathAddress( pathElement("subsystem", "elytron"), pathElement("custom-principal-transformer", name)); } @Override public String getName() { return name; } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { ModelNode addOperation = Util.createAddOperation(address); ModelNodeUtil.setIfNotNull(addOperation, "class-name", className); ModelNodeUtil.setIfNotNull(addOperation, "module", module); // Add optional key-value pairs as configuration object if(configuration.size() > 0) { StringBuilder configurationPairs = new StringBuilder(); configuration.forEach((key, value) -> configurationPairs.append(',').append(key).append('=').append(value)); configurationPairs.replace(0, 1, "{").append('}'); addOperation.get("configuration").set(configurationPairs.toString()); } Utils.applyUpdate(addOperation, client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(Util.createRemoveOperation(address), client); } public static Builder builder() { return new Builder(); } /** Builder to register a custom principal transformer with Elytron. */ public static class Builder { private String name; private String className; private String module; private Map<String,String> configuration = new HashMap<>(); private Builder() {} public Builder withName(String name) { this.name = name; return this; } public Builder withClassName(final String className) { this.className = className; return this; } public Builder withModule(String module) { this.module = module; return this; } public Builder addConfiguration(String key, String value) { configuration.put(key, value); return this; } public Builder addConfigurations(Map<String, String> configuration) { this.configuration.putAll(configuration); return this; } public CustomPrincipalTransformer build() { return new CustomPrincipalTransformer(name, className, module, configuration); } } }
4,345
33.492063
123
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/ServerSslContext.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; /** * Interface representing Elytron server-ssl-context. * * @author Josef Cacek */ public interface ServerSslContext extends ConfigurableElement { }
1,230
36.30303
70
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SaslServerFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; /** * Interface representing Elytron sasl-server-factory capability. * * @author Josef Cacek */ public interface SaslServerFactory extends ConfigurableElement { }
1,243
36.69697
70
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/EJBApplicationSecurityDomainMapping.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * @author Jan Martiska */ public class EJBApplicationSecurityDomainMapping implements ConfigurableElement { private final String appDomain; private final String elytronDomain; public EJBApplicationSecurityDomainMapping(String appDomain, String elytronDomain) { this.appDomain = appDomain; this.elytronDomain = elytronDomain; } @Override public String getName() { return appDomain; } @Override public void create(CLIWrapper cli) throws Exception { cli.sendLine("/subsystem=ejb3/application-security-domain="+ appDomain +":add(security-domain="+elytronDomain+")"); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine("/subsystem=ejb3/application-security-domain="+ appDomain +":remove"); } }
1,962
34.053571
123
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/KeyManager.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; /** * Interface representing Elytron key-manager. * * @author Josef Cacek */ public interface KeyManager extends ConfigurableElement { }
1,217
35.909091
70
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/MappedRegexRealmMapper.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.security.common.elytron; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; /** * A {@link ConfigurableElement} to create a mapped regex realm mapper resource. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ public class MappedRegexRealmMapper implements ConfigurableElement { private final PathAddress address; private final String name; private final String pattern; private final String delegateRealmMapper; private final Map<String, String> realmMapping; MappedRegexRealmMapper(final String name, final String pattern, final String delegateRealmMapper, final Map<String, String> realmMapping) { this.name = name; this.address = PathAddress.pathAddress(PathElement.pathElement("subsystem", "elytron"), PathElement.pathElement("mapped-regex-realm-mapper", name)); this.pattern = pattern; this.delegateRealmMapper = delegateRealmMapper; this.realmMapping = realmMapping; } @Override public String getName() { return name; } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { ModelNode addOperation = Util.createAddOperation(address); addOperation.get("pattern").set(pattern); if (delegateRealmMapper != null) { addOperation.get("delegate-realm-mapper").set(delegateRealmMapper); } if (realmMapping.size() > 0) { ModelNode realmMapping = new ModelNode(); for (Entry<String, String> entry : this.realmMapping.entrySet()) { realmMapping.get(entry.getKey()).set(entry.getValue()); } addOperation.get("realm-map").set(realmMapping); } Utils.applyUpdate(addOperation, client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { ModelNode removeOperation = Util.createRemoveOperation(address); Utils.applyUpdate(removeOperation, client); } public static Builder builder(final String name) { return new Builder(name); } public static class Builder { private final String name; private String pattern; private String delegateRealmMapper; private Map<String, String> realmMapping = new HashMap<>(); Builder(final String name) { this.name = name; } public Builder withPattern(final String pattern) { this.pattern = pattern; return this; } public Builder withDelegateRealmMapper(final String delegateRealmMapper) { this.delegateRealmMapper = delegateRealmMapper; return this; } public Builder withRealmMapping(final String from, final String to) { realmMapping.put(from, to); return this; } public MappedRegexRealmMapper build() { return new MappedRegexRealmMapper(name, pattern, delegateRealmMapper, realmMapping); } } }
4,053
33.355932
156
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SimpleCredentialStore.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.jboss.as.test.shared.CliUtils.escapePath; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * Elytron credential store (keystore-based) configuration implementation. * * @author Josef Cacek */ public class SimpleCredentialStore extends AbstractConfigurableElement implements CredentialStore { // Let's use the Path type for keystore location even the CLI fragment functionality is not used here. private final Path keyStorePath; private final CredentialReference credential; private final String keyStoreType; private final Boolean create; private final Boolean modifiable; private final Map<String, String> aliases; private SimpleCredentialStore(Builder builder) { super(builder); this.keyStorePath = Objects.requireNonNull(builder.keyStorePath, "KeyStore path has to be provided"); this.credential = builder.credential; this.keyStoreType = builder.keyStoreType; this.create = builder.create; this.modifiable = builder.modifiable; this.aliases = Collections.unmodifiableMap(new HashMap<>(builder.aliases)); } @Override public void create(CLIWrapper cli) throws Exception { // /subsystem=elytron/credential-store=test:add(location=a,create=true,modifiable=true,implementation-properties={"keyStoreType"=>"JCEKS"}, // credential-reference={clear-text=pass123}) final StringBuilder sb = new StringBuilder("/subsystem=elytron/credential-store="); sb.append(name).append(":add(").append("location=") .append(escapePath(keyStorePath.getPath())); if (create != null) { sb.append(",").append("create=").append(create.toString()); } if (modifiable != null) { sb.append(",").append("modifiable=").append(modifiable.toString()); } if (keyStoreType != null) { sb.append(",") .append("implementation-properties={") .append("\"keyStoreType\"=>\"") .append(keyStoreType) .append("\"}"); } if (credential != null) { sb.append(",").append(credential.asString()); } if (isNotBlank(keyStorePath.getRelativeTo())) { sb.append(",").append("relative-to=\"").append(keyStorePath.getRelativeTo()).append("\""); } sb.append(")"); cli.sendLine(sb.toString()); for (Entry<String, String> entry : aliases.entrySet()) { // /subsystem=elytron/credential-store=test/alias=alias1:add(secret-value=mySecretValue) cli.sendLine(String.format("/subsystem=elytron/credential-store=%s:add-alias(alias=%s, secret-value=\"%s\")", name, entry.getKey(), entry.getValue())); } } /** * @see ConfigurableElement#remove(CLIWrapper) */ @Override public void remove(CLIWrapper cli) throws Exception { // remove aliases for (String alias : aliases.keySet()) { // lowercase alias used - https://issues.jboss.org/browse/WFLY-8131 cli.sendLine(String.format("/subsystem=elytron/credential-store=%s:remove-alias(alias=%s)", name, alias.toLowerCase(Locale.ROOT))); } cli.sendLine(String.format("/subsystem=elytron/credential-store=%s:remove()", name)); } /** * Creates builder to build {@link SimpleCredentialStore}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link SimpleCredentialStore}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private Path keyStorePath; private CredentialReference credential; private String keyStoreType; private Boolean create; private Boolean modifiable; private Map<String, String> aliases = new HashMap<>(); private Builder() { } public Builder withKeyStorePath(Path keyStorePath) { this.keyStorePath = keyStorePath; return this; } public Builder withCredential(CredentialReference credential) { this.credential = credential; return this; } public Builder withKeyStoreType(String keyStoreType) { this.keyStoreType = keyStoreType; return this; } public Builder withCreate(Boolean create) { this.create = create; return this; } public Builder withModifiable(Boolean modifiable) { this.modifiable = modifiable; return this; } /** * Adds a named secret (alias + secret value) to the map of aliases to be created in the credential store. * * @param alias alias for the secret * @param secret secret value * @return */ public Builder withAlias(String alias, String secret) { this.aliases.put(alias, secret); return this; } /** * Clears secrets map (aliases). * * @see #withAlias(String, String) */ public Builder clearAliases() { this.aliases.clear(); return this; } public SimpleCredentialStore build() { return new SimpleCredentialStore(this); } @Override protected Builder self() { return this; } } }
6,861
33.656566
147
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/EjbElytronDomainSetup.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; 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.STEPS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.wildfly.test.security.common.elytron.Utils.applyRemoveAllowReload; import static org.wildfly.test.security.common.elytron.Utils.applyUpdate; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.shared.ServerReload; import org.jboss.dmr.ModelNode; /** * Utility methods to create/remove simple security domains * * @author <a href="mailto:jkalina@redhat.com">Jan Kalina</a> */ public class EjbElytronDomainSetup implements ServerSetupTask { private static final String SUBSYSTEM_NAME = "elytron"; private static final String DEFAULT_SECURITY_DOMAIN_NAME = "elytron-tests"; private PathAddress saslAuthenticationAddress; private PathAddress remotingConnectorAddress; private PathAddress ejbDomainAddress; private final String securityDomainName; private String saslAuthenticationFactoryValue = null; public EjbElytronDomainSetup() { this(DEFAULT_SECURITY_DOMAIN_NAME); } public EjbElytronDomainSetup(final String securityDomainName) { this.securityDomainName = securityDomainName; } protected String getSecurityDomainName() { return securityDomainName; } protected String getSecurityRealmName() { return getSecurityDomainName() + "-ejb3-UsersRoles"; } protected String getEjbDomainName() { return getSecurityDomainName(); } protected String getSaslAuthenticationName() { return getSecurityDomainName(); } protected String getRemotingConnectorName() { return "http-remoting-connector"; } @Override public void setup(final ManagementClient managementClient, final String containerId) throws Exception { saslAuthenticationAddress = PathAddress.pathAddress() .append(SUBSYSTEM, SUBSYSTEM_NAME) .append("sasl-authentication-factory", getSaslAuthenticationName()); remotingConnectorAddress = PathAddress.pathAddress() .append(SUBSYSTEM, "remoting") .append("http-connector", getRemotingConnectorName()); ejbDomainAddress = PathAddress.pathAddress() .append(SUBSYSTEM, "ejb3") .append("application-security-domain", getEjbDomainName()); final ModelNode compositeOp = new ModelNode(); compositeOp.get(OP).set(ModelDescriptionConstants.COMPOSITE); compositeOp.get(OP_ADDR).setEmptyList(); ModelNode steps = compositeOp.get(STEPS); // /subsystem=elytron/sasl-authentication-factory=ejb3-tests-auth-fac:add(sasl-server-factory=configured,security-domain=EjbDomain,mechanism-configurations=[{mechanism-name=BASIC}]) ModelNode addSaslAuthentication = Util.createAddOperation(saslAuthenticationAddress); addSaslAuthentication.get("sasl-server-factory").set("configured"); addSaslAuthentication.get("security-domain").set(getSecurityDomainName()); addSaslAuthentication.get("mechanism-configurations").get(0).get("mechanism-name").set("JBOSS-LOCAL-USER"); addSaslAuthentication.get("mechanism-configurations").get(0).get("realm-mapper").set("local"); addSaslAuthentication.get("mechanism-configurations").get(1).get("mechanism-name").set("DIGEST-MD5"); addSaslAuthentication.get("mechanism-configurations").get(1).get("mechanism-realm-configurations").get(0).get("realm-name").set(getSecurityRealmName()); steps.add(addSaslAuthentication); // remoting connection with sasl-authentication-factory ModelNode saslAuthenticationFactoryNode = Utils.applyRead(managementClient.getControllerClient() ,Util.getReadAttributeOperation(remotingConnectorAddress, "sasl-authentication-factory"), false); if(saslAuthenticationFactoryNode.isDefined()){ saslAuthenticationFactoryValue = saslAuthenticationFactoryNode.asString(); } ModelNode updateRemotingConnector = Util.getWriteAttributeOperation(remotingConnectorAddress, "sasl-authentication-factory", getSaslAuthenticationName()); steps.add(updateRemotingConnector); // /subsystem=ejb3/application-security-domain=ejb3-tests:add(security-domain=ApplicationDomain) ModelNode addEjbDomain = Util.createAddOperation(ejbDomainAddress); addEjbDomain.get("security-domain").set(getSecurityDomainName()); steps.add(addEjbDomain); applyUpdate(managementClient.getControllerClient(), compositeOp, false); // TODO: add {"allow-resource-service-restart" => true} to ejbDomainAddress write-attribute operation once WFLY-8793 / JBEAP-10955 is fixed // and remove this reload ServerReload.reloadIfRequired(managementClient); } @Override public void tearDown(final ManagementClient managementClient, final String containerId) { try { ModelNode restoreSaslOperation; if (saslAuthenticationFactoryValue != null) { restoreSaslOperation = Util.getWriteAttributeOperation(remotingConnectorAddress, "sasl-authentication-factory", saslAuthenticationFactoryValue); } else { restoreSaslOperation = Util.getUndefineAttributeOperation(remotingConnectorAddress, "sasl-authentication-factory"); } applyUpdate(managementClient.getControllerClient(), restoreSaslOperation, false); } catch (Exception e) { throw new RuntimeException(e); } applyRemoveAllowReload(managementClient.getControllerClient(), ejbDomainAddress, false); // TODO: add {"allow-resource-service-restart" => true} to ejbDomainAddress write-attribute operation once WFLY-8793 / JBEAP-10955 is fixed // and remove this reload try { ServerReload.reloadIfRequired(managementClient); } catch (Exception e) { throw new RuntimeException(e); } applyRemoveAllowReload(managementClient.getControllerClient(), saslAuthenticationAddress, false); } }
7,652
44.553571
202
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/FileAuditLog.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.apache.commons.lang3.StringUtils.isNotBlank; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * Helper class for adding "file-audit-log" attributes into CLI commands. * * @author Jan Tymel */ public class FileAuditLog extends AbstractConfigurableElement { private final String format; private final Boolean paramSynchronized; private final String path; private final String relativeTo; private final String encoding; private FileAuditLog(Builder builder) { super(builder); this.format = builder.format; this.paramSynchronized = builder.paramSynchronized; this.path = builder.path; this.relativeTo = builder.relativeTo; this.encoding = builder.encoding; } @Override public void create(CLIWrapper cli) throws Exception { StringBuilder command = new StringBuilder("/subsystem=elytron/file-audit-log=").append(name) .append(":add("); if (isNotBlank(format)) { command.append("format=\"").append(format).append("\", "); } if (paramSynchronized != null) { command.append("synchronized=").append(paramSynchronized).append(", "); } if (isNotBlank(path)) { command.append("path=\"").append(path).append("\", "); } if (isNotBlank(relativeTo)) { command.append("relative-to=\"").append(relativeTo).append("\", "); } if (isNotBlank(encoding)) { command.append("encoding=\"").append(encoding).append("\", "); } command.append(")"); cli.sendLine(command.toString()); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/file-audit-log=%s:remove()", name)); } /** * Creates builder to build {@link FileAuditLog}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link FileAuditLog}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String path; private String relativeTo; private Boolean paramSynchronized; private String format; private String encoding; private Builder() { } public Builder withPath(String path) { this.path = path; return this; } public Builder withRelativeTo(String relativeTo) { this.relativeTo = relativeTo; return this; } public Builder withSynchronized(boolean paramSynchronized) { this.paramSynchronized = paramSynchronized; return this; } public Builder withFormat(String format) { this.format = format; return this; } public Builder withEncoding(String encoding) { this.encoding = encoding; return this; } public FileAuditLog build() { return new FileAuditLog(this); } @Override protected Builder self() { return this; } } }
4,318
30.071942
100
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/CredentialReference.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.apache.commons.lang3.StringUtils.isNotBlank; import org.jboss.dmr.ModelNode; /** * Helper class for adding "credential-reference" attributes into CLI commands. * * @author Josef Cacek */ public class CredentialReference implements CliFragment { public static final CredentialReference EMPTY = CredentialReference.builder().build(); private final String store; private final String alias; private final String clearText; private CredentialReference(Builder builder) { this.store = builder.store; this.alias = builder.alias; this.clearText = builder.clearText; } @Override public String asString() { StringBuilder sb = new StringBuilder(); if (isNotBlank(alias) || isNotBlank(clearText) || isNotBlank(store)) { sb.append("credential-reference={ "); if (isNotBlank(alias)) { sb.append(String.format("alias=\"%s\", ", alias)); } if (isNotBlank(store)) { sb.append(String.format("store=\"%s\", ", store)); } if (isNotBlank(clearText)) { sb.append(String.format("clear-text=\"%s\"", clearText)); } sb.append("}, "); } return sb.toString(); } public ModelNode asModelNode() { ModelNode credentialReference = new ModelNode(); if (alias != null) { credentialReference.get("alias").set(alias); } if (store != null) { credentialReference.get("store").set(store); } if (clearText != null) { credentialReference.get("clear-text").set(clearText); } return credentialReference.asObject(); } /** * Creates builder to build {@link CredentialReference}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link CredentialReference}. */ public static final class Builder { private String store; private String alias; private String clearText; private Builder() { } public Builder withStore(String store) { this.store = store; return this; } public Builder withAlias(String alias) { this.alias = alias; return this; } public Builder withClearText(String clearText) { this.clearText = clearText; return this; } public CredentialReference build() { return new CredentialReference(this); } } }
3,739
29.655738
90
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/RegexPrincipalTransformer.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.security.common.elytron; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; /** * A {@link ConfigurableElement} to define a regex principal transformer. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ public class RegexPrincipalTransformer implements ConfigurableElement { private final PathAddress address; private final String name; private final String pattern; private final String replacement; private final boolean replaceAll; RegexPrincipalTransformer(String name, String pattern, String replacement, boolean replaceAll) { this.name = name; this.address = PathAddress.pathAddress(PathElement.pathElement("subsystem", "elytron"), PathElement.pathElement("regex-principal-transformer", name)); this.pattern = pattern; this.replacement = replacement; this.replaceAll = replaceAll; } @Override public String getName() { return name; } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { ModelNode addOperation = Util.createAddOperation(address); addOperation.get("pattern").set(pattern); addOperation.get("replacement").set(replacement); addOperation.get("replace-all").set(replaceAll); Utils.applyUpdate(addOperation, client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { ModelNode removeOperation = Util.createRemoveOperation(address); Utils.applyUpdate(removeOperation, client); } public static Builder builder(final String name) { return new Builder(name); } public static class Builder { private final String name; private String pattern; private String replacement; private boolean replaceAll; Builder(final String name) { this.name = name; } public Builder withPattern(final String pattern) { this.pattern = pattern; return this; } public Builder withReplacement(final String replacement) { this.replacement = replacement; return this; } public Builder replaceAll(final boolean replaceAll) { this.replaceAll = replaceAll; return this; } public RegexPrincipalTransformer build() { return new RegexPrincipalTransformer(name, pattern, replacement, replaceAll); } } }
3,455
30.706422
158
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/ClientSslContext.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; /** * Interface representing Elytron server-ssl-context. * * @author Jan Tymel */ public interface ClientSslContext extends ConfigurableElement { }
1,228
36.242424
70
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/ConstantRoleMapper.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import java.util.Objects; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; /** * Configuration for constant-permission-mapper Elytron resource. * * @author Josef Cacek */ public class ConstantRoleMapper extends AbstractConfigurableElement implements RoleMapper { private static final String CONSTANT_ROLE_MAPPER = "constant-role-mapper"; private static final PathAddress PATH_ELYTRON = PathAddress.pathAddress().append("subsystem", "elytron"); private final String[] roles; private ConstantRoleMapper(Builder builder) { super(builder); this.roles = Objects.requireNonNull(builder.roles, "Roles must be provided"); } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { ModelNode op = Util.createAddOperation(PATH_ELYTRON.append(CONSTANT_ROLE_MAPPER, name)); ModelNode rolesNode = op.get("roles"); for (String role : roles) { rolesNode.add(role); } Utils.applyUpdate(op, client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(Util.createRemoveOperation(PATH_ELYTRON.append(CONSTANT_ROLE_MAPPER, name)), client); } public static Builder builder() { return new Builder(); } /** * Builder for this class. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String[] roles; private Builder() { } @Override protected Builder self() { return this; } public ConstantRoleMapper build() { return new ConstantRoleMapper(this); } public Builder withRoles(String... roles) { this.roles = roles; return this; } } }
3,205
32.747368
111
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/Path.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.jboss.as.test.shared.CliUtils.escapePath; /** * Helper class for adding "path" and "relative-to" attributes into CLI commands. * * @author Josef Cacek */ public class Path implements CliFragment { public static final Path EMPTY = Path.builder().build(); private final String path; private final String relativeTo; private Path(Builder builder) { this.path = builder.path; this.relativeTo = builder.relativeTo; } public String getPath() { return path; } public String getRelativeTo() { return relativeTo; } /** * Generates part of CLI string in form "[path=..., [relative-to=..., ]" */ @Override public String asString() { StringBuilder sb = new StringBuilder(); if (isNotBlank(path)) { sb.append(String.format("path=\"%s\", ", escapePath(path))); if (isNotBlank(relativeTo)) { sb.append(String.format("relative-to=\"%s\"", relativeTo)); } } return sb.toString(); } /** * Creates builder to build {@link Path}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link Path}. */ public static final class Builder { private String path; private String relativeTo; private Builder() { } public Builder withPath(String path) { this.path = path; return this; } public Builder withRelativeTo(String relativeTo) { this.relativeTo = relativeTo; return this; } public Path build() { return new Path(this); } } }
2,918
27.339806
81
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SimpleAuthConfig.java
/* * Copyright 2017 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.security.common.elytron; import java.util.Properties; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * Elytron authentication configuration implementation. * * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> */ public class SimpleAuthConfig extends AbstractConfigurableElement { private final Boolean anonymous; private final Boolean allowAllMechanisms; private final String[] allowSaslMechanisms; private final String[] forbidSaslMechanisms; private final Properties mechanismProperties; private final String authenticationName; private final String authorizationName; private final CredentialReference credentialReference; private final String extendsAttr; private final String host; private final String port; private final String protocol; private final String realm; private final String securityDomain; private SimpleAuthConfig(final Builder builder) { super(builder); this.anonymous = builder.anonymous; this.allowAllMechanisms = builder.allowAllMechanisms; this.allowSaslMechanisms = builder.allowSaslMechanisms; this.forbidSaslMechanisms = builder.forbidSaslMechanisms; this.mechanismProperties = builder.mechanismProperties; this.authenticationName = builder.authenticationName; this.authorizationName = builder.authorizationName; this.credentialReference = builder.credentialReference; this.extendsAttr = builder.extendsAttr; this.host = builder.host; this.port = builder.port; this.protocol = builder.protocol; this.realm = builder.realm; this.securityDomain = builder.securityDomain; } @Override public void create(CLIWrapper cli) throws Exception { final StringBuilder sb = new StringBuilder("/subsystem=elytron/authentication-configuration=\""); sb.append(name).append("\":add("); if (anonymous != null) { sb.append(anonymous.booleanValue() == true ? "" : "!").append("anonymous, "); } if (allowAllMechanisms != null) { sb.append(allowAllMechanisms.booleanValue() == true ? "" : "!").append("allow-all-mechanisms, "); } if (allowSaslMechanisms != null && allowSaslMechanisms.length > 0) { sb.append("allow-sasl-mechanisms=["); for (String mech : allowSaslMechanisms) { sb.append(mech).append(" "); } sb.append("], "); } if (forbidSaslMechanisms != null && forbidSaslMechanisms.length > 0) { sb.append("forbid-sasl-mechanisms=["); for (String mech : forbidSaslMechanisms) { sb.append(mech).append(" "); } sb.append("], "); } if (mechanismProperties != null && !mechanismProperties.isEmpty()) { sb.append("mechanism-properties={"); for (Object key : mechanismProperties.keySet()) { sb.append(key.toString()).append("=").append(mechanismProperties.getProperty(key.toString())); sb.append(", "); } sb.append("}, "); } if (authenticationName != null && !authenticationName.isEmpty()) { sb.append(String.format("authentication-name=\"%s\", ", authenticationName)); } if (authorizationName != null && !authorizationName.isEmpty()) { sb.append(String.format("authorization-name=\"%s\", ", authorizationName)); } if (credentialReference != null) { sb.append(credentialReference.asString()); } if (extendsAttr != null && !extendsAttr.isEmpty()) { sb.append(String.format("extends=\"%s\", ", extendsAttr)); } if (host != null && !host.isEmpty()) { sb.append(String.format("host=\"%s\", ", host)); } if (port != null && !port.isEmpty()) { sb.append(String.format("port=\"%s\", ", port)); } if (protocol != null && !protocol.isEmpty()) { sb.append(String.format("protocol=\"%s\", ", protocol)); } if (realm != null && !realm.isEmpty()) { sb.append(String.format("realm=\"%s\", ", realm)); } if (securityDomain != null && !securityDomain.isEmpty()) { sb.append(String.format("security-domain=\"%s\", ", securityDomain)); } sb.append(")"); cli.sendLine(sb.toString()); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/authentication-configuration=\"%s\":remove", name)); } public static Builder builder() { return new Builder(); } public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private Boolean anonymous; private Boolean allowAllMechanisms; private String[] allowSaslMechanisms; private String[] forbidSaslMechanisms; private Properties mechanismProperties; private String authenticationName; private String authorizationName; private CredentialReference credentialReference; private String extendsAttr; private String host; private String port; private String protocol; private String realm; private String securityDomain; private Builder() { } public Builder allowAnonymous(final Boolean allowAnonymous) { this.anonymous = allowAnonymous; return this; } public Builder allowAllMechanisms(final Boolean allowAllMechanisms) { this.allowAllMechanisms = allowAllMechanisms; return this; } public Builder withAllowedSaslMechanisms(final String... allowedSaslMechanisms) { this.allowSaslMechanisms = allowedSaslMechanisms; return this; } public Builder withForbiddenSaslMechanisms(final String... forbiddenSaslMechanisms) { this.forbidSaslMechanisms = forbiddenSaslMechanisms; return this; } public Builder withMechanismProperties(final Properties mechanismProperties) { this.mechanismProperties = mechanismProperties; return this; } public Builder withAuthenticationName(final String authenticationName) { this.authenticationName = authenticationName; return this; } public Builder withAuthorizationName(final String authorizationName) { this.authorizationName = authorizationName; return this; } public Builder withCredentialReference(final CredentialReference credentialReference) { this.credentialReference = credentialReference; return this; } public Builder withExtends(final String extendsAttr) { this.extendsAttr = extendsAttr; return this; } public Builder withHost(final String host) { this.host = host; return this; } public Builder withPort(final String port) { this.port = port; return this; } public Builder withProtocol(final String protocol) { this.protocol = protocol; return this; } public Builder withRealm(final String realm) { this.realm = realm; return this; } public Builder withSecurityDomain(final String securityDomain) { this.securityDomain = securityDomain; return this; } public SimpleAuthConfig build() { return new SimpleAuthConfig(this); } @Override protected Builder self() { return this; } } }
8,507
35.358974
110
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/HttpAuthenticationFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; /** * Interface representing Elytron http-authentication-factory capability. * * @author Jan Kalina */ public interface HttpAuthenticationFactory extends ConfigurableElement { }
1,258
37.151515
73
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SimpleTrustManager.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import java.util.List; import java.util.Objects; import org.apache.commons.lang3.StringUtils; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * Elytron trust-managers configuration implementation. * * @author Josef Cacek */ public class SimpleTrustManager extends AbstractConfigurableElement implements TrustManager { private final String keyStore; private final String algorithm; private final int maximumCertPath; private final Boolean onlyLeafCert; private final Boolean softFail; private final Ocsp ocsp; private final CertificateRevocationList crl; private final List<CertificateRevocationList> crls; private SimpleTrustManager(Builder builder) { super(builder); this.keyStore = Objects.requireNonNull(builder.keyStore, "Key-store name has to be provided"); this.algorithm = builder.algorithm; this.maximumCertPath = builder.maximumCertPath; this.softFail = builder.softFail; this.onlyLeafCert = builder.onlyLeafCert; this.ocsp = builder.ocsp; this.crl = builder.crl; this.crls = builder.crls; } @Override public void create(CLIWrapper cli) throws Exception { StringBuilder cliLine = new StringBuilder("/subsystem=elytron/trust-manager=").append(name).append(":add("); // Already appends ',' after itself if defined. if (ocsp != null) { cliLine.append(ocsp.asString()); } // Already appends ',' after itself if defined. if (crl != null) { cliLine.append("certificate-revocation-list="); cliLine.append(crl.asString()); cliLine.append(", "); } // certificate-revocation-list and certificate-revocation-lists are mutually exclusive else if (crls != null) { cliLine.append("certificate-revocation-lists=["); for (int i = 0; i < crls.size(); i++) { cliLine.append(crls.get(i).asString()); // only append comma as long as there is another CRL to add to list if (i != crls.size() - 1) cliLine.append(", "); } cliLine.append("], "); } if (StringUtils.isNotBlank(keyStore)) { cliLine.append("key-store=\"").append(keyStore).append("\""); } String alg; if (StringUtils.isNotBlank(algorithm)) { alg = algorithm; } else { alg = "SunX509"; } cliLine.append(",algorithm=\"").append(alg).append("\""); if (softFail != null) { cliLine.append(",soft-fail=\"").append(softFail).append("\""); } if (onlyLeafCert != null) { cliLine.append(",only-leaf-cert=\"").append(onlyLeafCert).append("\""); } if (maximumCertPath > -1) { cliLine.append(",maximum-cert-path=\"").append(maximumCertPath).append("\""); } cliLine.append(")"); cli.sendLine(cliLine.toString()); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/trust-manager=%s:remove()", name)); } /** * Creates builder to build {@link SimpleTrustManager}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link SimpleTrustManager}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String keyStore; private String algorithm; private int maximumCertPath = -1; private Boolean onlyLeafCert; private Boolean softFail; private Ocsp ocsp; private CertificateRevocationList crl; private List<CertificateRevocationList> crls; private Builder() { } public Builder withKeyStore(String keyStore) { this.keyStore = keyStore; return this; } public Builder withAlgorithm(String algorithm) { this.algorithm = algorithm; return this; } public Builder withMaximumCertPath(int maximumCertPath) { this.maximumCertPath = maximumCertPath; return this; } public Builder withOnlyLeafCert(boolean onlyLeafCert) { this.onlyLeafCert = onlyLeafCert; return this; } public Builder withSoftFail(boolean softFail) { this.softFail = softFail; return this; } public Builder withOcsp(Ocsp ocsp) { this.ocsp = ocsp; return this; } public Builder withCrl(CertificateRevocationList crl) { this.crl = crl; return this; } public Builder withCrls(List<CertificateRevocationList> crls) { this.crls = crls; return this; } public SimpleTrustManager build() { return new SimpleTrustManager(this); } @Override protected Builder self() { return this; } } }
6,243
31.020513
116
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/TokenRealm.java
/* * Copyright 2020 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.security.common.elytron; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.dmr.ModelNode; /** * A {@link ConfigurableElement} to define the token-realm resource within the Elytron subsystem. * * @author Ondrej Kotek */ public class TokenRealm implements SecurityRealm { private final PathAddress address; private final String name; private final Jwt jwt; private final Oauth2Introspection oauth2Introspection; private final String principalClaim; TokenRealm(final String name, final Jwt jwt, final Oauth2Introspection oauth2Introspection, final String principalClaim) { this.address = PathAddress.pathAddress(PathElement.pathElement("subsystem", "elytron"), PathElement.pathElement("token-realm", name)); this.name = name; this.jwt = jwt; this.oauth2Introspection = oauth2Introspection; this.principalClaim = principalClaim; } @Override public String getName() { return name; } public ModelNode getAddOperation() { ModelNode addOperation = Util.createAddOperation(address); addOperation.get("token-realm"); if (principalClaim != null) { addOperation.get("principal-claim").set(principalClaim); } if (jwt != null) { ModelNode jwtProperties = new ModelNode(); if (jwt.getAudience() != null) { ModelNode audienceList = jwtProperties.get("audience"); for (String audienceEntry : jwt.getAudience()) { audienceList.add(audienceEntry); } } if (jwt.getIssuer() != null) { ModelNode issuerList = jwtProperties.get("issuer"); for (String issuerEntry : jwt.getIssuer()) { issuerList.add(issuerEntry); } } if (jwt.getCertificate() != null) { jwtProperties.get("certificate").set(jwt.getCertificate()); } if (jwt.getKeyStore() != null) { jwtProperties.get("key-store").set(jwt.getKeyStore()); } if (jwt.getPublicKey() != null) { jwtProperties.get("public-key").set(jwt.getPublicKey()); } if (jwtProperties.asListOrEmpty().isEmpty()) { addOperation.get("jwt").setEmptyObject(); } else { addOperation.get("jwt").set(jwtProperties.asObject()); } } if (oauth2Introspection != null) { ModelNode oauth2IntrospectionProperties = new ModelNode(); if (oauth2Introspection.getClientId() != null) { oauth2IntrospectionProperties.get("client-id").set(oauth2Introspection.getClientId()); } if (oauth2Introspection.getClientSecret() != null) { oauth2IntrospectionProperties.get("client-secret").set(oauth2Introspection.getClientSecret()); } if (oauth2Introspection.getClientSslContext() != null) { oauth2IntrospectionProperties.get("client-ssl-context").set(oauth2Introspection.getClientSslContext()); } if (oauth2Introspection.getHostNameVerificationPolicy() != null) { oauth2IntrospectionProperties.get("host-name-verification-policy").set(oauth2Introspection.getHostNameVerificationPolicy()); } if (oauth2Introspection.getIntrospectionUrl() != null) { oauth2IntrospectionProperties.get("introspection-url").set(oauth2Introspection.getIntrospectionUrl()); } if (oauth2IntrospectionProperties.asListOrEmpty().isEmpty()) { addOperation.get("oauth2-introspection").setEmptyObject(); } else { addOperation.get("oauth2-introspection").set(oauth2IntrospectionProperties.asObject()); } } return addOperation; } public ModelNode getRemoveOperation() { return Util.createRemoveOperation(address); } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { org.jboss.as.test.integration.security.common.Utils.applyUpdate(getAddOperation(), client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { org.jboss.as.test.integration.security.common.Utils.applyUpdate(getRemoveOperation(), client); } public static Builder builder(final String name) { return new Builder(name); } public static JwtBuilder jwtBuilder() { return new JwtBuilder(); } public static Oauth2IntrospectionBuilder oauth2IntrospectionBuilder() { return new Oauth2IntrospectionBuilder(); } public static final class Builder { private final String name; private Jwt jwt; private Oauth2Introspection oauth2Introspection; private String principalClaim; public Builder(String name) { this.name = name; } public Builder withJwt(Jwt jwt) { this.jwt = jwt; return this; } public Builder withOauth2Introspection(Oauth2Introspection oauth2Introspection) { this.oauth2Introspection = oauth2Introspection; return this; } public Builder withPrincipalClaim(String principalClaim) { this.principalClaim = principalClaim; return this; } public TokenRealm build() { return new TokenRealm(name, jwt, oauth2Introspection, principalClaim); } } public static final class Jwt { private final List<String> issuer; private final List<String> audience; private final String publicKey; private final String keyStore; private final String certificate; private Jwt(JwtBuilder builder) { this.issuer = builder.issuer; this.audience = builder.audience; this.publicKey = builder.publicKey; this.keyStore = builder.keyStore; this.certificate = builder.certificate; } public List<String> getIssuer() { return issuer; } public List<String> getAudience() { return audience; } public String getPublicKey() { return publicKey; } public String getKeyStore() { return keyStore; } public String getCertificate() { return certificate; } } public static final class JwtBuilder { private List<String> issuer; private List<String> audience; private String publicKey; private String keyStore; private String certificate; public JwtBuilder withIssuer(String... issuer) { if (this.issuer == null) { this.issuer = new ArrayList<String>(); } Collections.addAll(this.issuer, issuer); return this; } public JwtBuilder withAudience(String... audience) { if (this.audience == null) { this.audience = new ArrayList<String>(); } Collections.addAll(this.audience, audience); return this; } public JwtBuilder withPublicKey(String publicKey) { this.publicKey = publicKey; return this; } public JwtBuilder withKeyStore(String keyStore) { this.keyStore = keyStore; return this; } public JwtBuilder withCertificate(String certificate) { this.certificate = certificate; return this; } public Jwt build() { return new Jwt(this); } } public static final class Oauth2Introspection { private final String clientId; private final String clientSecret; private final String introspectionUrl; private final String clientSslContext; private final String hostNameVerificationPolicy; private Oauth2Introspection(Oauth2IntrospectionBuilder builder) { this.clientId = builder.clientId; this.clientSecret = builder.clientSecret; this.introspectionUrl = builder.introspectionUrl; this.clientSslContext = builder.clientSslContext; this.hostNameVerificationPolicy = builder.hostNameVerificationPolicy; } public String getClientId() { return clientId; } public String getClientSecret() { return clientSecret; } public String getIntrospectionUrl() { return introspectionUrl; } public String getClientSslContext() { return clientSslContext; } public String getHostNameVerificationPolicy() { return hostNameVerificationPolicy; } } public static final class Oauth2IntrospectionBuilder { private String clientId; private String clientSecret; private String introspectionUrl; private String clientSslContext; private String hostNameVerificationPolicy; public Oauth2IntrospectionBuilder withClientId(String clientId) { this.clientId = clientId; return this; } public Oauth2IntrospectionBuilder withClientSecret(String clientSecret) { this.clientSecret = clientSecret; return this; } public Oauth2IntrospectionBuilder withIntrospectionUrl(String introspectionUrl) { this.introspectionUrl = introspectionUrl; return this; } public Oauth2IntrospectionBuilder withClientSslContext(String clientSslContext) { this.clientSslContext = clientSslContext; return this; } public Oauth2IntrospectionBuilder withHostNameVerificationPolicy(String hostNameVerificationPolicy) { this.hostNameVerificationPolicy = hostNameVerificationPolicy; return this; } public Oauth2Introspection build() { return new Oauth2Introspection(this); } } }
11,178
31.879412
142
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/ConstantPermissionMapper.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.wildfly.test.security.common.ModelNodeUtil.setIfNotNull; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; /** * Configuration for constant-permission-mapper Elytron resource. * * @author Josef Cacek */ public class ConstantPermissionMapper extends AbstractConfigurableElement implements PermissionMapper { private static final String CONSTANT_PERMISSION_MAPPER = "constant-permission-mapper"; private static final PathAddress PATH_ELYTRON = PathAddress.pathAddress().append("subsystem", "elytron"); private final PermissionRef[] permissions; private ConstantPermissionMapper(Builder builder) { super(builder); this.permissions = builder.permissions; } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { ModelNode op = Util.createAddOperation(PATH_ELYTRON.append(CONSTANT_PERMISSION_MAPPER, name)); if (permissions != null) { ModelNode permissionsNode = op.get("permissions"); for (PermissionRef permissionRef : permissions) { ModelNode permissionRefNode = new ModelNode(); permissionRefNode.get("class-name").set(permissionRef.getClassName()); setIfNotNull(permissionRefNode, "module", permissionRef.getModule()); setIfNotNull(permissionRefNode, "target-name", permissionRef.getTargetName()); setIfNotNull(permissionRefNode, "action", permissionRef.getAction()); permissionsNode.add(permissionRefNode); } } Utils.applyUpdate(op, client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(Util.createRemoveOperation(PATH_ELYTRON.append(CONSTANT_PERMISSION_MAPPER, name)), client); } public static Builder builder() { return new Builder(); } /** * Builder for this class. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private PermissionRef[] permissions; private Builder() { } @Override protected Builder self() { return this; } public ConstantPermissionMapper build() { return new ConstantPermissionMapper(this); } public Builder withPermissions(PermissionRef... permissions) { this.permissions = permissions; return this; } } }
3,857
37.19802
117
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/Utils.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALLOW_RESOURCE_SERVICE_RESTART; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS; import java.io.IOException; import java.util.List; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.OperationBuilder; import org.jboss.as.controller.operations.common.Util; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; /** * Utility methods for test configuration. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ class Utils { private static final Logger LOGGER = Logger.getLogger(Utils.class); static void applyUpdates(final ModelControllerClient client, final List<ModelNode> updates) { for (ModelNode update : updates) { try { applyUpdate(client, update, false); } catch (Exception e) { throw new RuntimeException(e); } } } static void applyUpdate(final ModelControllerClient client, ModelNode update, boolean allowFailure) throws IOException { ModelNode result = client.execute(new OperationBuilder(update).build()); if (result.hasDefined("outcome") && (allowFailure || "success".equals(result.get("outcome").asString()))) { if (result.hasDefined("result")) { LOGGER.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")); } } static ModelNode applyRead(final ModelControllerClient client, ModelNode read, boolean allowFailure) throws IOException { ModelNode result = client.execute(new OperationBuilder(read).build()); if (result.hasDefined("outcome") && (allowFailure || "success".equals(result.get("outcome").asString()))) { return 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")); } } static void applyRemoveAllowReload(final ModelControllerClient client, PathAddress address, boolean allowFailure) { ModelNode op = Util.createRemoveOperation(address); op.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true); try { applyUpdate(client, op, allowFailure); } catch (IOException e) { throw new RuntimeException(e); } } }
3,947
41.913043
125
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SaslAuthenticationFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; /** * Interface representing Elytron sasl-authentication-factory capability. * * @author Josef Cacek */ public interface SaslAuthenticationFactory extends ConfigurableElement { }
1,259
37.181818
73
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/KeyStoreRealm.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import java.util.Objects; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * Elytron key-store-realm configuration implementation. * * @author Ondrej Kotek */ public class KeyStoreRealm extends AbstractConfigurableElement { private final String keyStore; private KeyStoreRealm(Builder builder) { super(builder); this.keyStore = Objects.requireNonNull(builder.keyStore, "Key-store name has to be provided"); } @Override public void create(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/key-store-realm=%s:add(key-store=\"%s\")", name, keyStore)); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/key-store-realm=%s:remove()", name)); } /** * Creates builder to build {@link KeyStoreRealm}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link KeyStoreRealm}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String keyStore; private Builder() { } public Builder withKeyStore(String keyStore) { this.keyStore = keyStore; return this; } public KeyStoreRealm build() { return new KeyStoreRealm(this); } @Override protected Builder self() { return this; } } }
2,640
29.709302
115
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/ConstantPrincipalTransformer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; /** * Elytron constant-principal-transformer configuration implementation. * * @author Josef Cacek */ public class ConstantPrincipalTransformer extends AbstractConstantHelper { private ConstantPrincipalTransformer(Builder builder) { super(builder); } @Override protected String getConstantElytronType() { return "constant-principal-transformer"; } /** * Creates builder. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder pattern for the class. */ public static final class Builder extends AbstractConstantHelper.Builder<Builder> { private Builder() { } public ConstantPrincipalTransformer build() { return new ConstantPrincipalTransformer(this); } @Override protected Builder self() { return this; } } }
2,022
28.318841
87
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SimpleClientSslContext.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import java.util.Arrays; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * Elytron client-ssl-context configuration implementation. * * @author Jan Tymel */ public class SimpleClientSslContext extends AbstractConfigurableElement implements ClientSslContext { private final String keyManager; private final String trustManager; private final String[] protocols; private SimpleClientSslContext(Builder builder) { super(builder); this.keyManager = builder.keyManagers; this.trustManager = builder.trustManager; this.protocols = builder.protocols; } @Override public void create(CLIWrapper cli) throws Exception { // /subsystem=elytron/client-ssl-context=twoWaySSC:add(key-manager=twoWayKM,protocols=["TLSv1.2"], // trust-manager=twoWayTM) StringBuilder sb = new StringBuilder("/subsystem=elytron/client-ssl-context=").append(name).append(":add("); if (StringUtils.isNotBlank(keyManager)) { sb.append("key-manager=\"").append(keyManager).append("\", "); } if (protocols != null) { sb.append("protocols=[") .append(Arrays.stream(protocols).map(s -> "\"" + s + "\"").collect(Collectors.joining(", "))).append("], "); } if (StringUtils.isNotBlank(trustManager)) { sb.append("trust-manager=\"").append(trustManager).append("\", "); } cli.sendLine(sb.toString()); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/client-ssl-context=%s:remove()", name)); } /** * Creates builder to build {@link SimpleServerSslContext}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link SimpleServerSslContext}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String keyManagers; private String trustManager; private String[] protocols; private Builder() { } public Builder withKeyManagers(String keyManagers) { this.keyManagers = keyManagers; return this; } public Builder withTrustManager(String trustManager) { this.trustManager = trustManager; return this; } public Builder withProtocols(String... protocols) { this.protocols = protocols; return this; } public SimpleClientSslContext build() { return new SimpleClientSslContext(this); } @Override protected Builder self() { return this; } } }
3,955
33.103448
128
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/MechanismRealmConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.wildfly.test.security.common.ModelNodeUtil.setIfNotNull; import java.util.Objects; import org.jboss.dmr.ModelNode; /** * Object which holds single instance from mechanism-realm-configurations list. * * @author Josef Cacek */ public class MechanismRealmConfiguration extends AbstractMechanismConfiguration { private final String realmName; private MechanismRealmConfiguration(Builder builder) { super(builder); this.realmName = Objects.requireNonNull(builder.realmName, "Realm name must not be null."); } public String getRealmName() { return realmName; } /** * Creates builder to build {@link MechanismRealmConfiguration}. * * @return created builder */ public static Builder builder() { return new Builder(); } @Override public ModelNode toModelNode() { ModelNode node = super.toModelNode(); setIfNotNull(node, "realm-name", realmName); return node; } /** * Builder to build {@link MechanismRealmConfiguration}. */ public static final class Builder extends AbstractMechanismConfiguration.Builder<Builder> { private String realmName; private Builder() { } public Builder withRealmName(String realmName) { this.realmName = realmName; return this; } public MechanismRealmConfiguration build() { return new MechanismRealmConfiguration(this); } @Override protected Builder self() { return this; } } }
2,679
28.450549
99
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SimplePermissionMapper.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * @author Jan Martiska */ public class SimplePermissionMapper extends AbstractConfigurableElement implements PermissionMapper { private final List<PermissionMapping> mappings; private final MappingMode mappingMode; private SimplePermissionMapper(Builder builder) { super(builder); this.mappings = builder.mappings; this.mappingMode = builder.mappingMode; } @Override public void create(CLIWrapper cli) throws Exception { final StringBuilder cliCommand = new StringBuilder(); cliCommand.append("/subsystem=elytron/simple-permission-mapper=") .append(name) .append(":add("); if (mappingMode != null) { cliCommand.append("mapping-mode=").append(mappingMode.toString()).append(","); } cliCommand.append("permission-mappings=["); cliCommand.append(mappings .stream() .map(PermissionMapping::toCLIString) .collect(Collectors.joining(","))); cliCommand.append("]"); cliCommand.append(")"); cli.sendLine(cliCommand.toString()); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine("/subsystem=elytron/simple-permission-mapper=" + name + ":remove"); } public static Builder builder() { return new Builder(); } /** * Builder to build {@link UndertowSslContext}. The name attribute refers to ssl-context capability name. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private MappingMode mappingMode; private List<PermissionMapping> mappings; public Builder() { mappings = new ArrayList<>(); } @Override protected Builder self() { return this; } public SimplePermissionMapper build() { return new SimplePermissionMapper(this); } public Builder mappingMode(MappingMode mappingMode) { this.mappingMode = mappingMode; return this; } public Builder permissionMapping(PermissionMapping mapping) { this.mappings.add(mapping); return this; } public Builder permissionMappings(PermissionMapping... mappings) { this.mappings.addAll(Arrays.asList(mappings)); return this; } } public static final class PermissionMapping { private final List<PermissionRef> permissions; private final List<String> principals; private final List<String> roles; private PermissionMapping(Builder builder) { this.permissions = builder.permissions; this.principals = builder.principals; this.roles = builder.roles; } public List<PermissionRef> getPermissions() { return permissions; } public List<String> getPrincipals() { return principals; } public List<String> getRoles() { return roles; } public static Builder builder() { return new Builder(); } public String toCLIString() { StringBuilder result = new StringBuilder(); result.append("{permissions=["); result.append(permissions.stream() .map(PermissionRef::toCLIString) .collect(Collectors.joining(","))); result.append("]"); if (principals.size() > 0) { result.append(",principals=["); result.append(StringUtils.join(principals, ",")); result.append("]"); } if (roles.size() > 0) { result.append(",roles=["); result.append(StringUtils.join(roles, ",")); result.append("]"); } result.append("}"); return result.toString(); } public static final class Builder { private List<PermissionRef> permissions; private List<String> principals; private List<String> roles; public Builder() { permissions = new ArrayList<>(); principals = new ArrayList<>(); roles = new ArrayList<>(); } public Builder withPermissions(PermissionRef... permissions) { this.permissions.addAll(Arrays.asList(permissions)); return this; } public Builder withPrincipals(String... principals) { this.principals.addAll(Arrays.asList(principals)); return this; } public Builder withRoles(String... roles) { this.roles.addAll(Arrays.asList(roles)); return this; } public PermissionMapping build() { return new PermissionMapping(this); } } } }
6,342
30.715
109
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/AbstractUserAttributeValuesCapableElement.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; /** * Abstract parent for {@link ConfigurableElement} implementations which are able to configure (and provide) users and roles. * It extends {@link AbstractConfigurableElement} and holds user list to be created. * * @author Josef Cacek */ public abstract class AbstractUserAttributeValuesCapableElement extends AbstractConfigurableElement implements UsersAttributeValuesCapableElement { private final List<UserWithAttributeValues> usersWithValues; protected AbstractUserAttributeValuesCapableElement(Builder<?> builder) { super(builder); this.usersWithValues = Collections.unmodifiableList(new ArrayList<>(builder.usersWithValues)); } @Override public List<UserWithAttributeValues> getUsersWithAttributeValues() { return usersWithValues; } /** * Builder to build {@link AbstractUserAttributeValuesCapableElement}. */ public abstract static class Builder<T extends Builder<T>> extends AbstractConfigurableElement.Builder<T> { private List<UserWithAttributeValues> usersWithValues = new ArrayList<>(); protected Builder() { } /** * Adds the given user to list of users in the domain. * * @param userWithValues not-null {@link UserWithAttributeValues} instance */ public final T withUser(UserWithAttributeValues userWithValues) { this.usersWithValues.add(Objects.requireNonNull(userWithValues, "Provided user must not be null.")); return self(); } /** * Shortcut method for {@link #withUser(UserWithAttributeValues)} one. * * @param username must not be null * @param password must not be null * @param values values to be assigned to user (may be null) */ public final T withUser(String username, String password, String... values) { this.usersWithValues.add(UserWithAttributeValues.builder().withName(username).withPassword(password).withValues(values).build()); return self(); } } }
3,260
38.289157
147
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/PropertiesRealm.java
/* * Copyright 2016 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.security.common.elytron; import static org.jboss.as.test.integration.security.common.Utils.createTemporaryFolder; import static org.jboss.as.test.shared.CliUtils.asAbsolutePath; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import org.apache.commons.io.FileUtils; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.logging.Logger; /** * Configuration for properties-realms Elytron resource. * * @author Josef Cacek */ public class PropertiesRealm extends AbstractUserAttributeValuesCapableElement implements SecurityRealm { private static final Logger LOGGER = Logger.getLogger(PropertiesRealm.class); private final String groupsAttribute; private final boolean plainText; // true by default private File tempFolder; private PropertiesRealm(Builder builder) { super(builder); this.groupsAttribute = builder.groupsAttribute; this.plainText = builder.plainText; } @Override public void create(CLIWrapper cli) throws Exception { this.tempFolder = createTemporaryFolder("ely-" + name); final Properties usersProperties = new Properties(); final Properties rolesProperties = new Properties(); for (UserWithAttributeValues user : getUsersWithAttributeValues()) { usersProperties.setProperty(user.getName(), user.getPassword()); rolesProperties.setProperty(user.getName(), String.join(",", user.getValues())); } File usersFile = writeProperties(usersProperties, "users.properties"); File rolesFile = writeProperties(rolesProperties, "roles.properties"); // /subsystem=elytron/properties-realm=test:add(users-properties={path=/tmp/users.properties, plain-text=true}, // groups-properties={path=/tmp/groups.properties}, groups-attribute="groups") final String groupsAttrStr = groupsAttribute == null ? "" : String.format(", groups-attribute=\"%s\"", groupsAttribute); cli.sendLine(String.format( "/subsystem=elytron/properties-realm=%s:add(users-properties={path=\"%s\", plain-text=%b}, groups-properties={path=\"%s\"}%s)", name, asAbsolutePath(usersFile), plainText, asAbsolutePath(rolesFile), groupsAttrStr)); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/properties-realm=%s:remove()", name)); FileUtils.deleteQuietly(tempFolder); tempFolder = null; } /** * Creates builder to build {@link PropertiesRealm}. * * @return created builder */ public static Builder builder() { return new Builder(); } private File writeProperties(Properties properties, String fileName) throws IOException { File result = new File(tempFolder, fileName); LOGGER.debugv("Creating property file {0}", result); try (FileOutputStream fos = new FileOutputStream(result)) { if (plainText) { properties.store(fos, null); } else { properties.store(fos, "$REALM_NAME=" + name + "$"); } } return result; } /** * Builder to build {@link PropertiesRealm}. */ public static final class Builder extends AbstractUserAttributeValuesCapableElement.Builder<Builder> { private String groupsAttribute; private boolean plainText = true; private Builder() { } public Builder withGroupsAttribute(String groupsAttribute) { this.groupsAttribute = groupsAttribute; return this; } public Builder withPlainText(boolean plainText) { this.plainText = plainText; return this; } public PropertiesRealm build() { return new PropertiesRealm(this); } @Override public Builder self() { return this; } } }
4,641
34.984496
143
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/PropertyFileAuthzBasedDomain.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.jboss.as.test.shared.CliUtils.asAbsolutePath; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Objects; import java.util.Properties; import org.apache.commons.io.FileUtils; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.logging.Logger; import org.wildfly.security.auth.permission.LoginPermission; /** * Elytron Security domain implementation which uses {@code properties-realm} to hold the users and roles for * authorization and given realm for authentication. * <p> * For this given domain are created also following Elytron resources (with the name based on the domain name): * <ul> * <li>properties-realm (name has "-authzRealm" suffix)</li> * <li>aggregate-realm (name has "-aggregateRealm" suffix)</li> * <li>simple-role-decoder</li> * <li>constant-permission-mapper</li> * </ul> * </p> * * @author Ondrej Kotek */ public class PropertyFileAuthzBasedDomain extends AbstractUserAttributeValuesCapableElement implements SecurityDomain { private static final Logger LOGGER = Logger.getLogger(PropertyFileAuthzBasedDomain.class); private final String principalDecoder; private final String authnRealm; private final String authzRealm; private final String aggregateRealm; private File tempFolder; private PropertyFileAuthzBasedDomain(Builder builder) { super(builder); this.principalDecoder = builder.principalDecoder; this.authnRealm = Objects.requireNonNull(builder.authnRealm, "Realm for authentication must not be null"); this.authzRealm = this.name + "-authzRealm"; this.aggregateRealm = this.name + "-aggregateRealm"; } @Override public void create(CLIWrapper cli) throws Exception { tempFolder = createTemporaryFolder("ely-" + getName()); final Properties usersProperties = new Properties(); final Properties rolesProperties = new Properties(); for (UserWithAttributeValues user : getUsersWithAttributeValues()) { usersProperties.setProperty(user.getName(), user.getPassword()); rolesProperties.setProperty(user.getName(), String.join(",", user.getValues())); } File usersFile = writeProperties(usersProperties, "users.properties"); File rolesFile = writeProperties(rolesProperties, "roles.properties"); // /subsystem=elytron/properties-realm=test:add(users-properties={path=/tmp/users.properties, plain-text=true}, // groups-properties={path=/tmp/groups.properties}) cli.sendLine(String.format( "/subsystem=elytron/properties-realm=%s:add(users-properties={path=\"%s\", plain-text=true}, groups-properties={path=\"%s\"})", authzRealm, asAbsolutePath(usersFile), asAbsolutePath(rolesFile))); // /subsystem=elytron/aggregate-realm=test-aggregateRealm:add(authentication-realm=test,authorization-realm=test-authzRealm) cli.sendLine(String.format( "/subsystem=elytron/aggregate-realm=%s:add(authentication-realm=%s,authorization-realm=%s)", aggregateRealm, authnRealm, authzRealm)); // /subsystem=elytron/simple-role-decoder=test:add(attribute=groups) cli.sendLine(String.format("/subsystem=elytron/simple-role-decoder=%s:add(attribute=groups)", name)); // /subsystem=elytron/constant-permission-mapper=test:add(permissions=[{class-name="org.wildfly.security.auth.permission.LoginPermission"}]) cli.sendLine(String.format("/subsystem=elytron/constant-permission-mapper=%s:add(permissions=[{class-name=\"%s\"}])", name, LoginPermission.class.getName())); // /subsystem=elytron/security-domain=test:add(default-realm=test-aggregateRealm, permission-mapper=test, // principal-decoder=test,realms=[{role-decoder=test, realm=test-aggregateRealm}]) StringBuilder command = new StringBuilder("/subsystem=elytron/security-domain=").append(name) .append(":add(default-realm=").append(aggregateRealm) .append(",permission-mapper=").append(name) .append(",realms=[{role-decoder=").append(name).append(",realm=").append(aggregateRealm).append("}]"); if (principalDecoder != null) { command.append(",principal-decoder=").append(principalDecoder); } command.append(")"); cli.sendLine(String.format(command.toString())); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/security-domain=%s:remove()", name)); cli.sendLine(String.format("/subsystem=elytron/constant-permission-mapper=%s:remove()", name)); cli.sendLine(String.format("/subsystem=elytron/simple-role-decoder=%s:remove()", name)); cli.sendLine(String.format("/subsystem=elytron/aggregate-realm=%s:remove()", aggregateRealm)); cli.sendLine(String.format("/subsystem=elytron/properties-realm=%s:remove()", authzRealm)); FileUtils.deleteQuietly(tempFolder); } /** * Creates builder to build {@link PropertyFileBasedDomain}. * * @return created builder */ public static Builder builder() { return new Builder(); } public static final class Builder extends AbstractUserAttributeValuesCapableElement.Builder<Builder> { private String authnRealm; private String principalDecoder; private Builder() { } public Builder withAuthnRealm(String authnRealm) { this.authnRealm = authnRealm; return this; } public Builder withPrincipalDecoder(String principalDecoder) { this.principalDecoder = principalDecoder; return this; } public PropertyFileAuthzBasedDomain build() { return new PropertyFileAuthzBasedDomain(this); } @Override protected Builder self() { return this; } } private File writeProperties(Properties properties, String fileName) throws IOException { File result = new File(tempFolder, fileName); LOGGER.debugv("Creating property file {0}", result); try (FileOutputStream fos = new FileOutputStream(result)) { // comment $REALM_NAME is just a workaround for https://issues.jboss.org/browse/WFLY-7104 properties.store(fos, "$REALM_NAME=" + name + "$"); } return result; } /** * Creates a temporary folder name with given name prefix. * * @param prefix folder name prefix * @return created folder */ private static File createTemporaryFolder(String prefix) throws IOException { File file = File.createTempFile(prefix, "", null); LOGGER.debugv("Creating temporary folder {0}", file); file.delete(); file.mkdir(); return file; } }
8,025
41.919786
148
java