package org.jboss.fuse.vault.karaf;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.HashMap;
import java.util.Map;

import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import org.junit.Test;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;

import static org.assertj.core.api.Assertions.assertThat;

public class JmxGuardIntegrationTest extends BaseWithVaultSetupTest {

    @Configuration
    public Option[] configuration() throws Exception {
        return withSystemProperties();
    }

    @Test
    public void shouldNotAllowJmxAccessToUnauthenticatedPrincipals() throws Exception {
        final JMXServiceURL karafViaJmx = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1099/karaf-root");

        final Map<String, Object> environment = new HashMap<>();
        final String[] credentials = {"karaf", "karaf"};
        environment.put(JMXConnector.CREDENTIALS, credentials);

        final JMXConnector connector = JMXConnectorFactory.connect(karafViaJmx, environment);

        final MBeanServerConnection connection = connector.getMBeanServerConnection();

        final RuntimeMXBean runtimeBean = ManagementFactory.newPlatformMXBeanProxy(connection, "java.lang:type=Runtime",
                RuntimeMXBean.class);

        final Map<String, String> systemProperties = runtimeBean.getSystemProperties();

        assertThat(systemProperties).containsEntry("prop", "<sensitive>");
    }
}

@@ -383,16 +383,47 @@
 t.Test;%0A
+import org.ops4j.net.FreePort;%0A
 import o
@@ -547,16 +547,113 @@
 ertThat;
+%0Aimport static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
 %0A%0Apublic
@@ -717,16 +717,42 @@
 Test %7B%0A%0A
+    private int jmxPort;%0A%0A
     @Con
@@ -829,36 +829,216 @@
     
-return withSystemProperties(
+jmxPort = new FreePort(10000, 20000).getPort();%0A%0A        return withSystemProperties(editConfigurationFilePut(%22etc/org.apache.karaf.management.cfg%22, %22rmiServerPort%22,%0A                Integer.toString(jmxPort))
 );%0A 
@@ -1201,16 +1201,33 @@
 viceURL(
+%0A                
 %22service
@@ -1263,12 +1263,23 @@
 ost:
-1099
+%22 + jmxPort + %22
 /kar

Use a free port in JMX integration test