Search in sources :

Example 41 with Template

use of org.apache.knox.gateway.util.urltemplate.Template in project knox by apache.

the class SecureQueryEncodeProcessorTest method testSimpleQueryEncoding.

@Test
public void testSimpleQueryEncoding() throws Exception {
    AliasService as = EasyMock.createNiceMock(AliasService.class);
    String secret = "sdkjfhsdkjfhsdfs";
    EasyMock.expect(as.getPasswordFromAliasForCluster("test-cluster-name", "encryptQueryString")).andReturn(secret.toCharArray()).anyTimes();
    CryptoService cryptoService = new DefaultCryptoService();
    ((DefaultCryptoService) cryptoService).setAliasService(as);
    GatewayServices gatewayServices = EasyMock.createNiceMock(GatewayServices.class);
    EasyMock.expect(gatewayServices.getService(GatewayServices.CRYPTO_SERVICE)).andReturn(cryptoService);
    UrlRewriteEnvironment environment = EasyMock.createNiceMock(UrlRewriteEnvironment.class);
    EasyMock.expect(environment.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE)).andReturn(gatewayServices).anyTimes();
    EasyMock.expect(environment.getAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE)).andReturn(Arrays.asList("test-cluster-name")).anyTimes();
    Template inTemplate = Parser.parseLiteral("http://host:0/root/path?query");
    UrlRewriteContext context = EasyMock.createNiceMock(UrlRewriteContext.class);
    EasyMock.expect(context.getCurrentUrl()).andReturn(inTemplate);
    Capture<Template> outTemplate = new Capture<Template>();
    context.setCurrentUrl(EasyMock.capture(outTemplate));
    EasyMock.replay(environment, context);
    SecureQueryEncodeDescriptor descriptor = new SecureQueryEncodeDescriptor();
    SecureQueryEncodeProcessor processor = new SecureQueryEncodeProcessor();
    processor.initialize(environment, descriptor);
    processor.process(context);
    BASE64Encoder encoder = new BASE64Encoder();
    String encQuery = encoder.encode("query".getBytes("utf-8"));
    encQuery = encQuery.replaceAll("\\=", "");
    String outExpect = "http://host:0/root/path?_=" + encQuery;
    String outActual = outTemplate.getValue().toString();
    assertThat(outActual, is(outExpect));
}
Also used : UrlRewriteEnvironment(org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment) GatewayServices(org.apache.knox.gateway.services.GatewayServices) AliasService(org.apache.knox.gateway.services.security.AliasService) BASE64Encoder(sun.misc.BASE64Encoder) UrlRewriteContext(org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext) Capture(org.easymock.Capture) Template(org.apache.knox.gateway.util.urltemplate.Template) DefaultCryptoService(org.apache.knox.gateway.services.security.impl.DefaultCryptoService) CryptoService(org.apache.knox.gateway.services.security.CryptoService) DefaultCryptoService(org.apache.knox.gateway.services.security.impl.DefaultCryptoService) Test(org.junit.Test)

Example 42 with Template

use of org.apache.knox.gateway.util.urltemplate.Template in project knox by apache.

the class UrlRewriteProcessor method initializeRules.

private void initializeRules(UrlRewriteRulesDescriptor descriptor) {
    for (UrlRewriteRuleDescriptor ruleDescriptor : descriptor.getRules()) {
        try {
            UrlRewriteRuleProcessorHolder ruleProcessor = new UrlRewriteRuleProcessorHolder();
            ruleProcessor.initialize(environment, ruleDescriptor);
            if (!rules.containsKey(ruleDescriptor.name())) {
                rules.put(ruleDescriptor.name(), ruleProcessor);
            }
            Template template = ruleDescriptor.template();
            if (template != null) {
                EnumSet<Direction> directions = ruleDescriptor.directions();
                if (directions == null || directions.isEmpty()) {
                    inbound.add(template, ruleProcessor);
                    outbound.add(template, ruleProcessor);
                } else if (directions.contains(Direction.IN)) {
                    inbound.add(template, ruleProcessor);
                } else if (directions.contains(Direction.OUT)) {
                    outbound.add(template, ruleProcessor);
                }
            }
        } catch (Exception e) {
            LOG.failedToInitializeRewriteRules(e);
        }
    }
}
Also used : UrlRewriteRuleProcessorHolder(org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteRuleProcessorHolder) Template(org.apache.knox.gateway.util.urltemplate.Template)

Example 43 with Template

use of org.apache.knox.gateway.util.urltemplate.Template in project knox by apache.

the class SecureQueryEncryptDecryptProcessorTest method testEncryptBadDecrypt.

@Test
public void testEncryptBadDecrypt() throws Exception {
    Query query;
    Template origTemplate = Parser.parseLiteral("http://host:0/path/file?query-param-name=query-param-value");
    // Test encryption.  Results are left in encTemplate
    AliasService as = EasyMock.createNiceMock(AliasService.class);
    String secret = "sdkjfhsdkjfhsdfs";
    EasyMock.expect(as.getPasswordFromAliasForCluster("test-cluster-name", "encryptQueryString")).andReturn(secret.toCharArray()).anyTimes();
    CryptoService cryptoService = new DefaultCryptoService();
    ((DefaultCryptoService) cryptoService).setAliasService(as);
    GatewayServices gatewayServices = EasyMock.createNiceMock(GatewayServices.class);
    EasyMock.expect(gatewayServices.getService(GatewayServices.CRYPTO_SERVICE)).andReturn(cryptoService);
    UrlRewriteEnvironment encEnvironment = EasyMock.createNiceMock(UrlRewriteEnvironment.class);
    EasyMock.expect(encEnvironment.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE)).andReturn(gatewayServices).anyTimes();
    EasyMock.expect(encEnvironment.getAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE)).andReturn("test-cluster-name").anyTimes();
    UrlRewriteContext encContext = EasyMock.createNiceMock(UrlRewriteContext.class);
    EasyMock.expect(encContext.getCurrentUrl()).andReturn(origTemplate);
    Capture<Template> encTemplate = new Capture<Template>();
    encContext.setCurrentUrl(EasyMock.capture(encTemplate));
    EasyMock.replay(gatewayServices, as, encEnvironment, encContext);
    SecureQueryEncryptDescriptor descriptor = new SecureQueryEncryptDescriptor();
    SecureQueryEncryptProcessor processor = new SecureQueryEncryptProcessor();
    processor.initialize(encEnvironment, descriptor);
    processor.process(encContext);
    assertThat(encTemplate, notNullValue());
    query = encTemplate.getValue().getQuery().get("_");
    assertThat(query.getFirstValue().getPattern().length(), greaterThan(1));
    query = encTemplate.getValue().getQuery().get("query-param-name");
    assertThat(query, nullValue());
    // Test decryption with decode returning null
    gatewayServices = EasyMock.createNiceMock(GatewayServices.class);
    EasyMock.expect(gatewayServices.getService(GatewayServices.CRYPTO_SERVICE)).andReturn(cryptoService);
    as = EasyMock.createNiceMock(AliasService.class);
    EasyMock.expect(as.getPasswordFromAliasForCluster("test-cluster-name", "encryptQueryString")).andReturn(secret.toCharArray()).anyTimes();
    UrlRewriteEnvironment decEnvironment = EasyMock.createNiceMock(UrlRewriteEnvironment.class);
    EasyMock.expect(decEnvironment.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE)).andReturn(gatewayServices).anyTimes();
    EasyMock.expect(decEnvironment.getAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE)).andReturn("test-cluster-name").anyTimes();
    Params decParams = EasyMock.createNiceMock(Params.class);
    EasyMock.expect(decParams.resolve(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE)).andReturn(Arrays.asList("test-cluster-name")).anyTimes();
    UrlRewriteContext decContext = EasyMock.createNiceMock(UrlRewriteContext.class);
    EasyMock.expect(decContext.getCurrentUrl()).andReturn(encTemplate.getValue());
    EasyMock.expect(decContext.getParameters()).andReturn(decParams);
    Capture<Template> decTemplate = new Capture<Template>();
    decContext.setCurrentUrl(EasyMock.capture(decTemplate));
    SecureQueryDecryptDescriptor descriptor1 = new SecureQueryDecryptDescriptor();
    SecureQueryDecryptProcessor decProcessor = EasyMock.createMockBuilder(SecureQueryDecryptProcessor.class).addMockedMethod(SecureQueryDecryptProcessor.class.getDeclaredMethod("decode", String.class)).createMock();
    EasyMock.expect(decProcessor.decode(EasyMock.anyObject(String.class))).andReturn(null);
    EasyMock.replay(gatewayServices, as, decEnvironment, decParams, decContext, decProcessor);
    decProcessor.initialize(decEnvironment, descriptor1);
    UrlRewriteStepStatus status = decProcessor.process(decContext);
    Assert.assertTrue((status == UrlRewriteStepStatus.FAILURE));
}
Also used : UrlRewriteEnvironment(org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment) GatewayServices(org.apache.knox.gateway.services.GatewayServices) AliasService(org.apache.knox.gateway.services.security.AliasService) Query(org.apache.knox.gateway.util.urltemplate.Query) Params(org.apache.knox.gateway.util.urltemplate.Params) UrlRewriteContext(org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext) Capture(org.easymock.Capture) Template(org.apache.knox.gateway.util.urltemplate.Template) UrlRewriteStepStatus(org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus) DefaultCryptoService(org.apache.knox.gateway.services.security.impl.DefaultCryptoService) CryptoService(org.apache.knox.gateway.services.security.CryptoService) DefaultCryptoService(org.apache.knox.gateway.services.security.impl.DefaultCryptoService) Test(org.junit.Test)

Example 44 with Template

use of org.apache.knox.gateway.util.urltemplate.Template in project knox by apache.

the class SecureQueryEncryptDecryptProcessorTest method testEncryptDecrypt.

@Test
public void testEncryptDecrypt() throws Exception {
    Query query;
    Template origTemplate = Parser.parseLiteral("http://host:0/path/file?query-param-name=query-param-value");
    // Test encryption.  Results are left in encTemplate
    AliasService as = EasyMock.createNiceMock(AliasService.class);
    String secret = "sdkjfhsdkjfhsdfs";
    EasyMock.expect(as.getPasswordFromAliasForCluster("test-cluster-name", "encryptQueryString")).andReturn(secret.toCharArray()).anyTimes();
    CryptoService cryptoService = new DefaultCryptoService();
    ((DefaultCryptoService) cryptoService).setAliasService(as);
    GatewayServices gatewayServices = EasyMock.createNiceMock(GatewayServices.class);
    EasyMock.expect(gatewayServices.getService(GatewayServices.CRYPTO_SERVICE)).andReturn(cryptoService);
    UrlRewriteEnvironment encEnvironment = EasyMock.createNiceMock(UrlRewriteEnvironment.class);
    EasyMock.expect(encEnvironment.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE)).andReturn(gatewayServices).anyTimes();
    EasyMock.expect(encEnvironment.getAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE)).andReturn("test-cluster-name").anyTimes();
    UrlRewriteContext encContext = EasyMock.createNiceMock(UrlRewriteContext.class);
    EasyMock.expect(encContext.getCurrentUrl()).andReturn(origTemplate);
    Capture<Template> encTemplate = new Capture<Template>();
    encContext.setCurrentUrl(EasyMock.capture(encTemplate));
    EasyMock.replay(gatewayServices, as, encEnvironment, encContext);
    SecureQueryEncryptDescriptor descriptor = new SecureQueryEncryptDescriptor();
    SecureQueryEncryptProcessor processor = new SecureQueryEncryptProcessor();
    processor.initialize(encEnvironment, descriptor);
    processor.process(encContext);
    assertThat(encTemplate, notNullValue());
    query = encTemplate.getValue().getQuery().get("_");
    assertThat(query.getFirstValue().getPattern().length(), greaterThan(1));
    query = encTemplate.getValue().getQuery().get("query-param-name");
    assertThat(query, nullValue());
    // Test decryption.  Results are left in decTemplate.
    gatewayServices = EasyMock.createNiceMock(GatewayServices.class);
    EasyMock.expect(gatewayServices.getService(GatewayServices.CRYPTO_SERVICE)).andReturn(cryptoService);
    as = EasyMock.createNiceMock(AliasService.class);
    EasyMock.expect(as.getPasswordFromAliasForCluster("test-cluster-name", "encryptQueryString")).andReturn(secret.toCharArray()).anyTimes();
    UrlRewriteEnvironment decEnvironment = EasyMock.createNiceMock(UrlRewriteEnvironment.class);
    EasyMock.expect(decEnvironment.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE)).andReturn(gatewayServices).anyTimes();
    EasyMock.expect(decEnvironment.getAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE)).andReturn("test-cluster-name").anyTimes();
    Params decParams = EasyMock.createNiceMock(Params.class);
    EasyMock.expect(decParams.resolve(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE)).andReturn(Arrays.asList("test-cluster-name")).anyTimes();
    UrlRewriteContext decContext = EasyMock.createNiceMock(UrlRewriteContext.class);
    EasyMock.expect(decContext.getCurrentUrl()).andReturn(encTemplate.getValue());
    EasyMock.expect(decContext.getParameters()).andReturn(decParams);
    Capture<Template> decTemplate = new Capture<Template>();
    decContext.setCurrentUrl(EasyMock.capture(decTemplate));
    EasyMock.replay(gatewayServices, as, decEnvironment, decParams, decContext);
    SecureQueryDecryptDescriptor descriptor1 = new SecureQueryDecryptDescriptor();
    SecureQueryDecryptProcessor decProcessor = new SecureQueryDecryptProcessor();
    decProcessor.initialize(decEnvironment, descriptor1);
    decProcessor.process(decContext);
    assertThat(decTemplate, notNullValue());
    assertThat(decTemplate.getValue(), notNullValue());
    query = decTemplate.getValue().getQuery().get("query-param-name");
    assertThat(query.getFirstValue().getPattern(), is("query-param-value"));
    query = decTemplate.getValue().getQuery().get("_");
    assertThat(query, nullValue());
}
Also used : UrlRewriteEnvironment(org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment) GatewayServices(org.apache.knox.gateway.services.GatewayServices) AliasService(org.apache.knox.gateway.services.security.AliasService) Query(org.apache.knox.gateway.util.urltemplate.Query) Params(org.apache.knox.gateway.util.urltemplate.Params) UrlRewriteContext(org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext) Capture(org.easymock.Capture) Template(org.apache.knox.gateway.util.urltemplate.Template) DefaultCryptoService(org.apache.knox.gateway.services.security.impl.DefaultCryptoService) CryptoService(org.apache.knox.gateway.services.security.CryptoService) DefaultCryptoService(org.apache.knox.gateway.services.security.impl.DefaultCryptoService) Test(org.junit.Test)

Example 45 with Template

use of org.apache.knox.gateway.util.urltemplate.Template in project knox by apache.

the class GatewayFilter method doFilter.

@SuppressWarnings("unchecked")
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
    // TODO: The resulting pathInfo + query needs to be added to the servlet context somehow so that filters don't need to rebuild it.  This is done in HttpClientDispatch right now for example.
    String servlet = httpRequest.getServletPath();
    String path = httpRequest.getPathInfo();
    String query = httpRequest.getQueryString();
    String requestPath = (servlet == null ? "" : servlet) + (path == null ? "" : path);
    String requestPathWithQuery = requestPath + (query == null ? "" : "?" + query);
    Template pathWithQueryTemplate;
    try {
        pathWithQueryTemplate = Parser.parseLiteral(requestPathWithQuery);
    } catch (URISyntaxException e) {
        throw new ServletException(e);
    }
    String contextWithPathAndQuery = httpRequest.getContextPath() + requestPathWithQuery;
    LOG.receivedRequest(httpRequest.getMethod(), requestPath);
    servletRequest.setAttribute(AbstractGatewayFilter.SOURCE_REQUEST_URL_ATTRIBUTE_NAME, pathWithQueryTemplate);
    servletRequest.setAttribute(AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME, contextWithPathAndQuery);
    Matcher<Chain>.Match match = chains.match(pathWithQueryTemplate);
    // if there was no match then look for a default service for the topology
    if (match == null) {
        Topology topology = (Topology) servletRequest.getServletContext().getAttribute("org.apache.knox.gateway.topology");
        if (topology != null) {
            String defaultServicePath = topology.getDefaultServicePath();
            if (defaultServicePath != null) {
                try {
                    String newPathWithQuery = defaultServicePath + "/" + pathWithQueryTemplate;
                    match = chains.match(Parser.parseLiteral(newPathWithQuery));
                    String origUrl = ((HttpServletRequest) servletRequest).getRequestURL().toString();
                    String url = origUrl;
                    if (path.equals("/")) {
                        url += defaultServicePath;
                    } else {
                        int index = origUrl.indexOf(path);
                        url = origUrl.substring(0, index) + "/" + defaultServicePath + path;
                    }
                    String contextPath = defaultServicePath;
                    servletRequest = new ForwardedRequest((HttpServletRequest) servletRequest, contextPath, url);
                } catch (URISyntaxException e) {
                    throw new ServletException(e);
                }
            }
        }
    }
    assignCorrelationRequestId();
    // Populate Audit/correlation parameters
    AuditContext auditContext = auditService.getContext();
    auditContext.setTargetServiceName(match == null ? null : match.getValue().getResourceRole());
    auditContext.setRemoteIp(getRemoteAddress(servletRequest));
    auditContext.setRemoteHostname(servletRequest.getRemoteHost());
    auditor.audit(Action.ACCESS, contextWithPathAndQuery, ResourceType.URI, ActionOutcome.UNAVAILABLE, RES.requestMethod(((HttpServletRequest) servletRequest).getMethod()));
    if (match != null) {
        Chain chain = match.getValue();
        servletRequest.setAttribute(AbstractGatewayFilter.TARGET_SERVICE_ROLE, chain.getResourceRole());
        try {
            chain.doFilter(servletRequest, servletResponse);
        } catch (IOException | RuntimeException | ThreadDeath | ServletException e) {
            LOG.failedToExecuteFilter(e);
            auditor.audit(Action.ACCESS, contextWithPathAndQuery, ResourceType.URI, ActionOutcome.FAILURE);
            throw e;
        } catch (Throwable e) {
            LOG.failedToExecuteFilter(e);
            auditor.audit(Action.ACCESS, contextWithPathAndQuery, ResourceType.URI, ActionOutcome.FAILURE);
            throw new ServletException(e);
        } finally {
            // Make sure to destroy the correlationContext to prevent threading issues
            CorrelationServiceFactory.getCorrelationService().detachContext();
        }
    } else {
        LOG.failedToMatchPath(requestPath);
        httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        // Make sure to destroy the correlationContext to prevent threading issues
        CorrelationServiceFactory.getCorrelationService().detachContext();
    }
// KAM[ Don't do this or the Jetty default servlet will overwrite any response setup by the filter.
// filterChain.doFilter( servletRequest, servletResponse );
// ]
}
Also used : FilterChain(javax.servlet.FilterChain) Matcher(org.apache.knox.gateway.util.urltemplate.Matcher) HttpServletResponse(javax.servlet.http.HttpServletResponse) URISyntaxException(java.net.URISyntaxException) Topology(org.apache.knox.gateway.topology.Topology) IOException(java.io.IOException) AuditContext(org.apache.knox.gateway.audit.api.AuditContext) Template(org.apache.knox.gateway.util.urltemplate.Template) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException)

Aggregations

Template (org.apache.knox.gateway.util.urltemplate.Template)50 Test (org.junit.Test)23 UrlRewriteEnvironment (org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment)15 Resolver (org.apache.knox.gateway.util.urltemplate.Resolver)10 URISyntaxException (java.net.URISyntaxException)9 URL (java.net.URL)8 UrlRewriteProcessor (org.apache.knox.gateway.filter.rewrite.api.UrlRewriteProcessor)8 UrlRewriteRuleDescriptor (org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor)8 UrlRewriteRulesDescriptor (org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor)8 UrlRewriteActionRewriteDescriptorExt (org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteActionRewriteDescriptorExt)8 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 HttpServletResponse (javax.servlet.http.HttpServletResponse)7 UrlRewriteContext (org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext)6 GatewayServices (org.apache.knox.gateway.services.GatewayServices)5 Capture (org.easymock.Capture)5 Host (org.apache.knox.gateway.util.urltemplate.Host)4 Matcher (org.apache.knox.gateway.util.urltemplate.Matcher)4 Query (org.apache.knox.gateway.util.urltemplate.Query)4 URI (java.net.URI)3 UrlRewriteStepStatus (org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus)3