Search in sources :

Example 36 with GatewayConfig

use of org.apache.knox.gateway.config.GatewayConfig in project knox by apache.

the class RemoteConfigurationRegistryClientServiceTest method testZooKeeperWithSimpleRegistryConfig.

/**
 * Test a configuration for a secure remote registry, included in the gateway configuration.
 */
@Test
public void testZooKeeperWithSimpleRegistryConfig() throws Exception {
    final String AUTH_TYPE = "digest";
    final String REGISTRY_CLIENT_NAME = "zk-registry-name";
    final String PRINCIPAL = "knox";
    final String PWD = "knoxtest";
    final String CRED_ALIAS = "zkCredential";
    // Configure and start a secure ZK cluster
    TestingCluster zkCluster = setupAndStartSecureTestZooKeeper(PRINCIPAL, PWD);
    try {
        // Create the setup client for the test cluster, and initialize the test znodes
        CuratorFramework setupClient = initializeTestClientAndZNodes(zkCluster, PRINCIPAL);
        // Mock configuration
        GatewayConfig config = EasyMock.createNiceMock(GatewayConfig.class);
        final String registryConfigValue = GatewayConfig.REMOTE_CONFIG_REGISTRY_TYPE + "=" + ZooKeeperClientService.TYPE + ";" + GatewayConfig.REMOTE_CONFIG_REGISTRY_ADDRESS + "=" + zkCluster.getConnectString() + ";" + GatewayConfig.REMOTE_CONFIG_REGISTRY_AUTH_TYPE + "=" + AUTH_TYPE + ";" + GatewayConfig.REMOTE_CONFIG_REGISTRY_PRINCIPAL + "=" + PRINCIPAL + ";" + GatewayConfig.REMOTE_CONFIG_REGISTRY_CREDENTIAL_ALIAS + "=" + CRED_ALIAS;
        EasyMock.expect(config.getRemoteRegistryConfiguration(REGISTRY_CLIENT_NAME)).andReturn(registryConfigValue).anyTimes();
        EasyMock.expect(config.getRemoteRegistryConfigurationNames()).andReturn(Collections.singletonList(REGISTRY_CLIENT_NAME)).anyTimes();
        EasyMock.replay(config);
        doTestZooKeeperClient(setupClient, REGISTRY_CLIENT_NAME, config, CRED_ALIAS, PWD);
    } finally {
        zkCluster.stop();
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) TestingCluster(org.apache.curator.test.TestingCluster) GatewayConfig(org.apache.knox.gateway.config.GatewayConfig) Test(org.junit.Test)

Example 37 with GatewayConfig

use of org.apache.knox.gateway.config.GatewayConfig in project knox by apache.

the class ServiceTestResource method serviceTest.

@GET
@Produces({ APPLICATION_XML, APPLICATION_JSON })
public ServiceTestWrapper serviceTest(@QueryParam("username") String username, @QueryParam("password") String password) {
    List<ServiceTest> tests = new ArrayList<>();
    List<String> messages = new ArrayList<>();
    String authString;
    GatewayConfig config = (GatewayConfig) request.getServletContext().getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
    SSLContext ctx = null;
    CloseableHttpClient client;
    String id = getTopologyName();
    Topology topology = getTopology(id);
    // Create Authorization String
    if (username != null && password != null) {
        authString = "Basic " + Base64.encodeAsString((username + ":" + password).getBytes());
    } else if (request.getHeader("Authorization") != null) {
        authString = request.getHeader("Authorization");
    } else {
        authString = null;
    }
    // Attempt to build SSL context for HTTP client.
    try {
        ctx = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
    } catch (Exception e) {
        messages.add(e.getMessage());
    }
    // Initialize the HTTP client
    if (ctx == null) {
        client = HttpClients.createDefault();
    } else {
        client = HttpClients.custom().setSslcontext(ctx).build();
    }
    if (topology != null) {
        for (Service s : topology.getServices()) {
            List<String> urls = getServiceTestURLs(config, s.getRole(), topology);
            // Make sure we handle a case where no URLs are found.
            if (urls.size() <= 0) {
                ServiceTest test = new ServiceTest(s);
                test.setMessage("This service did not contain any test URLs");
            }
            for (String url : urls) {
                HttpGet req = new HttpGet();
                ServiceTest test = new ServiceTest(s, url);
                if (authString != null) {
                    req.setHeader("Authorization", authString);
                } else {
                    messages.add("No credentials provided. Expect HTTP 401 responses.");
                }
                try {
                    req.setURI(new URIBuilder(url).build());
                    CloseableHttpResponse res = client.execute(req);
                    String contentLength = "Content-Length:" + res.getEntity().getContentLength();
                    String contentType = (res.getEntity().getContentType() != null) ? res.getEntity().getContentType().toString() : "No-contenttype";
                    test.setResponseContent(contentLength + "," + contentType);
                    test.setHttpCode(res.getStatusLine().getStatusCode());
                    res.close();
                } catch (IOException e) {
                    messages.add("Exception: " + e.getMessage());
                    test.setMessage(e.getMessage());
                } catch (URISyntaxException e) {
                    test.setMessage(e.getMessage());
                } catch (Exception e) {
                    messages.add(e.getMessage());
                    test.setMessage(e.getMessage());
                } finally {
                    req.releaseConnection();
                    tests.add(test);
                }
            }
        }
    } else {
        messages.add("Topology " + id + " not found");
    }
    try {
        client.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    ServiceTestWrapper stw = new ServiceTestWrapper();
    stw.setTests(tests);
    stw.setMessages(messages);
    return stw;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) Service(org.apache.knox.gateway.topology.Service) TopologyService(org.apache.knox.gateway.services.topology.TopologyService) SSLContext(javax.net.ssl.SSLContext) Topology(org.apache.knox.gateway.topology.Topology) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URIBuilder(org.apache.http.client.utils.URIBuilder) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy) GatewayConfig(org.apache.knox.gateway.config.GatewayConfig) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 38 with GatewayConfig

use of org.apache.knox.gateway.config.GatewayConfig in project knox by apache.

the class ServiceTestResource method getTopologyName.

private String getTopologyName() {
    String ctxPath = request.getContextPath();
    GatewayConfig config = (GatewayConfig) request.getServletContext().getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
    String path = config.getGatewayPath();
    String topologyName = ctxPath.replace(path, "").replace("/", "");
    return topologyName;
}
Also used : GatewayConfig(org.apache.knox.gateway.config.GatewayConfig)

Example 39 with GatewayConfig

use of org.apache.knox.gateway.config.GatewayConfig in project knox by apache.

the class SimpleDescriptorHandlerFuncTest method testSimpleDescriptorHandlerQueryStringCredentialAliasCreation.

/**
 * KNOX-1136
 * <p>
 * Test that a credential store is created, and a encryptQueryString alias is defined, with a password that is not
 * random (but is derived from the master secret and the topology name).
 * <p>
 * N.B. This test depends on the NoOpServiceDiscovery extension being configured in META-INF/services
 */
@Test
public void testSimpleDescriptorHandlerQueryStringCredentialAliasCreation() throws Exception {
    final String testMasterSecret = "mysecret";
    final String discoveryType = "NO_OP";
    final String clusterName = "dummy";
    final Map<String, List<String>> serviceURLs = new HashMap<>();
    serviceURLs.put("RESOURCEMANAGER", Collections.singletonList("http://myhost:1234/resource"));
    File testRootDir = TestUtils.createTempDir(getClass().getSimpleName());
    File testConfDir = new File(testRootDir, "conf");
    File testProvDir = new File(testConfDir, "shared-providers");
    File testTopoDir = new File(testConfDir, "topologies");
    File testDeployDir = new File(testConfDir, "deployments");
    // Write the externalized provider config to a temp file
    File providerConfig = new File(testProvDir, "ambari-cluster-policy.xml");
    FileUtils.write(providerConfig, TEST_PROVIDER_CONFIG);
    File topologyFile = null;
    try {
        File destDir = new File(System.getProperty("java.io.tmpdir")).getCanonicalFile();
        // Mock out the simple descriptor
        SimpleDescriptor testDescriptor = EasyMock.createNiceMock(SimpleDescriptor.class);
        EasyMock.expect(testDescriptor.getName()).andReturn("mysimpledescriptor").anyTimes();
        EasyMock.expect(testDescriptor.getDiscoveryAddress()).andReturn(null).anyTimes();
        EasyMock.expect(testDescriptor.getDiscoveryType()).andReturn(discoveryType).anyTimes();
        EasyMock.expect(testDescriptor.getDiscoveryUser()).andReturn(null).anyTimes();
        EasyMock.expect(testDescriptor.getProviderConfig()).andReturn(providerConfig.getAbsolutePath()).anyTimes();
        EasyMock.expect(testDescriptor.getClusterName()).andReturn(clusterName).anyTimes();
        List<SimpleDescriptor.Service> serviceMocks = new ArrayList<>();
        for (String serviceName : serviceURLs.keySet()) {
            SimpleDescriptor.Service svc = EasyMock.createNiceMock(SimpleDescriptor.Service.class);
            EasyMock.expect(svc.getName()).andReturn(serviceName).anyTimes();
            EasyMock.expect(svc.getURLs()).andReturn(serviceURLs.get(serviceName)).anyTimes();
            EasyMock.expect(svc.getParams()).andReturn(Collections.emptyMap()).anyTimes();
            EasyMock.replay(svc);
            serviceMocks.add(svc);
        }
        EasyMock.expect(testDescriptor.getServices()).andReturn(serviceMocks).anyTimes();
        EasyMock.replay(testDescriptor);
        // Try setting up enough of the GatewayServer to support the test...
        GatewayConfig config = EasyMock.createNiceMock(GatewayConfig.class);
        InetSocketAddress gatewayAddress = new InetSocketAddress(0);
        EasyMock.expect(config.getGatewayTopologyDir()).andReturn(testTopoDir.getAbsolutePath()).anyTimes();
        EasyMock.expect(config.getGatewayDeploymentDir()).andReturn(testDeployDir.getAbsolutePath()).anyTimes();
        EasyMock.expect(config.getGatewayAddress()).andReturn(gatewayAddress).anyTimes();
        EasyMock.expect(config.getGatewayPortMappings()).andReturn(Collections.emptyMap()).anyTimes();
        EasyMock.replay(config);
        // Setup the Gateway Services
        GatewayServices gatewayServices = EasyMock.createNiceMock(GatewayServices.class);
        // Master Service
        MasterService ms = EasyMock.createNiceMock(MasterService.class);
        EasyMock.expect(ms.getMasterSecret()).andReturn(testMasterSecret.toCharArray()).anyTimes();
        EasyMock.replay(ms);
        EasyMock.expect(gatewayServices.getService("MasterService")).andReturn(ms).anyTimes();
        // Keystore Service
        KeystoreService ks = EasyMock.createNiceMock(KeystoreService.class);
        EasyMock.expect(ks.isCredentialStoreForClusterAvailable(testDescriptor.getName())).andReturn(false).once();
        ks.createCredentialStoreForCluster(testDescriptor.getName());
        EasyMock.expectLastCall().once();
        KeyStore credStore = EasyMock.createNiceMock(KeyStore.class);
        EasyMock.expect(ks.getCredentialStoreForCluster(testDescriptor.getName())).andReturn(credStore).anyTimes();
        EasyMock.replay(ks);
        EasyMock.expect(gatewayServices.getService(GatewayServices.KEYSTORE_SERVICE)).andReturn(ks).anyTimes();
        // Alias Service
        AliasService as = EasyMock.createNiceMock(AliasService.class);
        // Captures for validating the alias creation for a generated topology
        Capture<String> capturedCluster = EasyMock.newCapture();
        Capture<String> capturedAlias = EasyMock.newCapture();
        Capture<String> capturedPwd = EasyMock.newCapture();
        as.addAliasForCluster(capture(capturedCluster), capture(capturedAlias), capture(capturedPwd));
        EasyMock.expectLastCall().anyTimes();
        EasyMock.replay(as);
        EasyMock.expect(gatewayServices.getService(GatewayServices.ALIAS_SERVICE)).andReturn(as).anyTimes();
        // Topology Service
        TopologyService ts = EasyMock.createNiceMock(TopologyService.class);
        ts.addTopologyChangeListener(anyObject());
        EasyMock.expectLastCall().anyTimes();
        ts.reloadTopologies();
        EasyMock.expectLastCall().anyTimes();
        EasyMock.expect(ts.getTopologies()).andReturn(Collections.emptyList()).anyTimes();
        EasyMock.replay(ts);
        EasyMock.expect(gatewayServices.getService(GatewayServices.TOPOLOGY_SERVICE)).andReturn(ts).anyTimes();
        EasyMock.replay(gatewayServices);
        // Start a GatewayService with the GatewayServices mock
        GatewayServer server = GatewayServer.startGateway(config, gatewayServices);
        // Invoke the simple descriptor handler, which will also create the credential store
        // (because it doesn't exist) and the encryptQueryString alias
        Map<String, File> files = SimpleDescriptorHandler.handle(config, testDescriptor, providerConfig.getParentFile(), destDir);
        topologyFile = files.get("topology");
        // Validate the AliasService interaction
        assertEquals("Unexpected cluster name for the alias (should be the topology name).", testDescriptor.getName(), capturedCluster.getValue());
        assertEquals("Unexpected alias name.", "encryptQueryString", capturedAlias.getValue());
        assertEquals("Unexpected alias value (should be master secret + topology name.", testMasterSecret + testDescriptor.getName(), capturedPwd.getValue());
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    } finally {
        FileUtils.forceDelete(testRootDir);
        if (topologyFile != null) {
            topologyFile.delete();
        }
    }
}
Also used : GatewayServices(org.apache.knox.gateway.services.GatewayServices) AliasService(org.apache.knox.gateway.services.security.AliasService) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) AliasService(org.apache.knox.gateway.services.security.AliasService) MasterService(org.apache.knox.gateway.services.security.MasterService) KeystoreService(org.apache.knox.gateway.services.security.KeystoreService) TopologyService(org.apache.knox.gateway.services.topology.TopologyService) MasterService(org.apache.knox.gateway.services.security.MasterService) KeyStore(java.security.KeyStore) SimpleDescriptor(org.apache.knox.gateway.topology.simple.SimpleDescriptor) TopologyService(org.apache.knox.gateway.services.topology.TopologyService) ArrayList(java.util.ArrayList) List(java.util.List) KeystoreService(org.apache.knox.gateway.services.security.KeystoreService) File(java.io.File) GatewayConfig(org.apache.knox.gateway.config.GatewayConfig) Test(org.junit.Test)

Example 40 with GatewayConfig

use of org.apache.knox.gateway.config.GatewayConfig in project knox by apache.

the class DeploymentFactoryFuncTest method testDeploymentWithApplication.

@Test(timeout = MEDIUM_TIMEOUT)
public void testDeploymentWithApplication() throws Exception {
    LOG_ENTER();
    GatewayConfig config = new GatewayTestConfig();
    File targetDir = new File(System.getProperty("user.dir"), "target");
    File gatewayDir = new File(targetDir, "gateway-home-" + UUID.randomUUID());
    gatewayDir.mkdirs();
    ((GatewayTestConfig) config).setGatewayHomeDir(gatewayDir.getAbsolutePath());
    File deployDir = new File(config.getGatewayDeploymentDir());
    deployDir.mkdirs();
    URL serviceUrl = TestUtils.getResourceUrl(DeploymentFactoryFuncTest.class, "test-apps/minimal-test-app/service.xml");
    File serviceFile = new File(serviceUrl.toURI());
    File appsDir = serviceFile.getParentFile().getParentFile();
    ((GatewayTestConfig) config).setGatewayApplicationsDir(appsDir.getAbsolutePath());
    DefaultGatewayServices srvcs = new DefaultGatewayServices();
    Map<String, String> options = new HashMap<>();
    options.put("persist-master", "false");
    options.put("master", "password");
    try {
        DeploymentFactory.setGatewayServices(srvcs);
        srvcs.init(config, options);
    } catch (ServiceLifecycleException e) {
        // I18N not required.
        e.printStackTrace();
    }
    Topology topology = new Topology();
    topology.setName("test-topology");
    Application app;
    app = new Application();
    app.setName("minimal-test-app");
    app.addUrl("/minimal-test-app-path");
    topology.addApplication(app);
    EnterpriseArchive archive = DeploymentFactory.createDeployment(config, topology);
    assertThat(archive, notNullValue());
    Document doc;
    doc = XmlUtils.readXml(archive.get("META-INF/topology.xml").getAsset().openStream());
    assertThat(doc, notNullValue());
    doc = XmlUtils.readXml(archive.get("%2Fminimal-test-app-path/WEB-INF/gateway.xml").getAsset().openStream());
    assertThat(doc, notNullValue());
    // dump( doc );
    assertThat(doc, hasXPath("/gateway/resource/pattern", equalTo("/**?**")));
    assertThat(doc, hasXPath("/gateway/resource/filter[1]/role", equalTo("xforwardedheaders")));
    assertThat(doc, hasXPath("/gateway/resource/filter[1]/name", equalTo("XForwardedHeaderFilter")));
    assertThat(doc, hasXPath("/gateway/resource/filter[1]/class", equalTo(XForwardedHeaderFilter.class.getName())));
    assertThat(doc, hasXPath("/gateway/resource/filter[2]/role", equalTo("rewrite")));
    assertThat(doc, hasXPath("/gateway/resource/filter[2]/name", equalTo("url-rewrite")));
    assertThat(doc, hasXPath("/gateway/resource/filter[2]/class", equalTo(UrlRewriteServletFilter.class.getName())));
    LOG_EXIT();
}
Also used : EnterpriseArchive(org.jboss.shrinkwrap.api.spec.EnterpriseArchive) HashMap(java.util.HashMap) ServiceLifecycleException(org.apache.knox.gateway.services.ServiceLifecycleException) UrlRewriteServletFilter(org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletFilter) Topology(org.apache.knox.gateway.topology.Topology) Document(org.w3c.dom.Document) GatewayTestConfig(org.apache.knox.gateway.GatewayTestConfig) URL(java.net.URL) XForwardedHeaderFilter(org.apache.knox.gateway.filter.XForwardedHeaderFilter) DefaultGatewayServices(org.apache.knox.gateway.services.DefaultGatewayServices) File(java.io.File) Application(org.apache.knox.gateway.topology.Application) GatewayConfig(org.apache.knox.gateway.config.GatewayConfig) Test(org.junit.Test)

Aggregations

GatewayConfig (org.apache.knox.gateway.config.GatewayConfig)90 Test (org.junit.Test)67 File (java.io.File)31 HashMap (java.util.HashMap)24 GatewayConfigImpl (org.apache.knox.gateway.config.impl.GatewayConfigImpl)19 Topology (org.apache.knox.gateway.topology.Topology)17 ServiceLifecycleException (org.apache.knox.gateway.services.ServiceLifecycleException)13 HttpServletRequest (javax.servlet.http.HttpServletRequest)12 AliasService (org.apache.knox.gateway.services.security.AliasService)12 DefaultGatewayServices (org.apache.knox.gateway.services.DefaultGatewayServices)11 IOException (java.io.IOException)9 Service (org.apache.knox.gateway.topology.Service)9 Document (org.w3c.dom.Document)9 ArrayList (java.util.ArrayList)8 GatewayTestConfig (org.apache.knox.gateway.GatewayTestConfig)8 MasterService (org.apache.knox.gateway.services.security.MasterService)8 TopologyService (org.apache.knox.gateway.services.topology.TopologyService)8 KeystoreService (org.apache.knox.gateway.services.security.KeystoreService)7 EnterpriseArchive (org.jboss.shrinkwrap.api.spec.EnterpriseArchive)7 List (java.util.List)6