Search in sources :

Example 6 with AuditContext

use of org.apache.knox.gateway.audit.api.AuditContext 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)

Example 7 with AuditContext

use of org.apache.knox.gateway.audit.api.AuditContext in project knox by apache.

the class AbstractJWTFilter method continueWithEstablishedSecurityContext.

protected void continueWithEstablishedSecurityContext(Subject subject, final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException {
    Principal principal = (Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0];
    AuditContext context = auditService.getContext();
    if (context != null) {
        context.setUsername(principal.getName());
        String sourceUri = (String) request.getAttribute(AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME);
        if (sourceUri != null) {
            auditor.audit(Action.AUTHENTICATION, sourceUri, ResourceType.URI, ActionOutcome.SUCCESS);
        }
    }
    try {
        Subject.doAs(subject, new PrivilegedExceptionAction<Object>() {

            @Override
            public Object run() throws Exception {
                chain.doFilter(request, response);
                return null;
            }
        });
    } catch (PrivilegedActionException e) {
        Throwable t = e.getCause();
        if (t instanceof IOException) {
            throw (IOException) t;
        } else if (t instanceof ServletException) {
            throw (ServletException) t;
        } else {
            throw new ServletException(t);
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) PrivilegedActionException(java.security.PrivilegedActionException) PrimaryPrincipal(org.apache.knox.gateway.security.PrimaryPrincipal) IOException(java.io.IOException) PrimaryPrincipal(org.apache.knox.gateway.security.PrimaryPrincipal) Principal(java.security.Principal) AuditContext(org.apache.knox.gateway.audit.api.AuditContext) ServletException(javax.servlet.ServletException) TokenServiceException(org.apache.knox.gateway.services.security.token.TokenServiceException) ParseException(java.text.ParseException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException)

Example 8 with AuditContext

use of org.apache.knox.gateway.audit.api.AuditContext in project knox by apache.

the class AuditLayoutTest method testFullyFilledAuditEvent.

@Test
public void testFullyFilledAuditEvent() {
    AuditContext auditContext = auditService.createContext();
    auditContext.setProxyUsername(PROXYUSERNAME);
    auditContext.setSystemUsername(SYSTEMUSERNAME);
    auditContext.setUsername(USERNAME);
    auditContext.setRemoteHostname(HOST_NAME);
    auditContext.setRemoteIp(HOST_ADDRESS);
    auditContext.setTargetServiceName(TARGET_SERVICE);
    CorrelationContext correlationContext = correlationService.createContext();
    correlationContext.setRequestId(REQUEST_ID);
    correlationContext.setParentRequestId(PARENT_REQUEST_ID);
    correlationContext.setRootRequestId(ROOT_REQUEST_ID);
    auditor.audit(ACTION, RESOURCE_NAME, RESOURCE_TYPE, OUTCOME, MESSAGE);
    assertThat(CollectAppender.queue.size(), is(1));
    LoggingEvent event = CollectAppender.queue.iterator().next();
    SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
    String formatedDate = format.format(new Date(event.getTimeStamp()));
    // 14/01/24 12:40:24 1|2|3|audit.forward|hostaddress|WEBHDFS|username|proxy_username|system_username|action|resource_type|resource_name|outcome|message
    String expectedOutput = String.format(RECORD_PATTERN, formatedDate, ROOT_REQUEST_ID, PARENT_REQUEST_ID, REQUEST_ID, "audit.forward", HOST_ADDRESS, TARGET_SERVICE, USERNAME, PROXYUSERNAME, SYSTEMUSERNAME, ACTION, RESOURCE_TYPE, RESOURCE_NAME, OUTCOME, MESSAGE, AuditLayout.LINE_SEP);
    String auditOutput = layout.format(event);
    assertThat(auditOutput, is(expectedOutput));
}
Also used : LoggingEvent(org.apache.log4j.spi.LoggingEvent) CorrelationContext(org.apache.knox.gateway.audit.api.CorrelationContext) SimpleDateFormat(java.text.SimpleDateFormat) AuditContext(org.apache.knox.gateway.audit.api.AuditContext) Date(java.util.Date) Test(org.junit.Test)

Example 9 with AuditContext

use of org.apache.knox.gateway.audit.api.AuditContext in project knox by apache.

the class AuditLayout method format.

@Override
public String format(LoggingEvent event) {
    sb.setLength(0);
    dateFormat(sb, event);
    CorrelationContext cc = (CorrelationContext) event.getMDC(Log4jCorrelationService.MDC_CORRELATION_CONTEXT_KEY);
    AuditContext ac = (AuditContext) event.getMDC(Log4jAuditService.MDC_AUDIT_CONTEXT_KEY);
    appendParameter(cc == null ? null : cc.getRootRequestId());
    appendParameter(cc == null ? null : cc.getParentRequestId());
    appendParameter(cc == null ? null : cc.getRequestId());
    appendParameter(event.getLoggerName());
    appendParameter(ac == null ? null : ac.getRemoteIp());
    appendParameter(ac == null ? null : ac.getTargetServiceName());
    appendParameter(ac == null ? null : ac.getUsername());
    appendParameter(ac == null ? null : ac.getProxyUsername());
    appendParameter(ac == null ? null : ac.getSystemUsername());
    appendParameter((String) event.getMDC(AuditConstants.MDC_ACTION_KEY));
    appendParameter((String) event.getMDC(AuditConstants.MDC_RESOURCE_TYPE_KEY));
    appendParameter((String) event.getMDC(AuditConstants.MDC_RESOURCE_NAME_KEY));
    appendParameter((String) event.getMDC(AuditConstants.MDC_OUTCOME_KEY));
    String message = event.getRenderedMessage();
    sb.append(message == null ? "" : message).append(LINE_SEP);
    return sb.toString();
}
Also used : CorrelationContext(org.apache.knox.gateway.audit.api.CorrelationContext) AuditContext(org.apache.knox.gateway.audit.api.AuditContext)

Example 10 with AuditContext

use of org.apache.knox.gateway.audit.api.AuditContext in project knox by apache.

the class Log4jAuditService method detachContext.

@Override
public AuditContext detachContext() {
    AuditContext context = (AuditContext) MDC.get(MDC_AUDIT_CONTEXT_KEY);
    MDC.remove(MDC_AUDIT_CONTEXT_KEY);
    return context;
}
Also used : AuditContext(org.apache.knox.gateway.audit.api.AuditContext)

Aggregations

AuditContext (org.apache.knox.gateway.audit.api.AuditContext)11 CorrelationContext (org.apache.knox.gateway.audit.api.CorrelationContext)7 LoggingEvent (org.apache.log4j.spi.LoggingEvent)3 Test (org.junit.Test)3 IOException (java.io.IOException)2 ServletException (javax.servlet.ServletException)2 URISyntaxException (java.net.URISyntaxException)1 Principal (java.security.Principal)1 PrivilegedActionException (java.security.PrivilegedActionException)1 ParseException (java.text.ParseException)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1 FilterChain (javax.servlet.FilterChain)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 PrimaryPrincipal (org.apache.knox.gateway.security.PrimaryPrincipal)1 TokenServiceException (org.apache.knox.gateway.services.security.token.TokenServiceException)1 Topology (org.apache.knox.gateway.topology.Topology)1 Matcher (org.apache.knox.gateway.util.urltemplate.Matcher)1 Template (org.apache.knox.gateway.util.urltemplate.Template)1