Search in sources :

Example 31 with RequestInfo

use of com.nike.riposte.server.http.RequestInfo in project riposte by Nike-Inc.

the class BasicAuthSecurityValidatorTest method validateInvalidPassword.

@Test(expected = Unauthorized401Exception.class)
public void validateInvalidPassword() {
    RequestInfo mockRequest = mock(RequestInfo.class);
    doReturn(mock(HttpHeaders.class)).when(mockRequest).getHeaders();
    when(mockRequest.getHeaders().get("Authorization")).thenReturn(calcAuthHeader(USERNAME, "blah"));
    underTest.validateSecureRequestForEndpoint(mockRequest, mockEndpoint1);
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) RequestInfo(com.nike.riposte.server.http.RequestInfo) Test(org.junit.Test)

Example 32 with RequestInfo

use of com.nike.riposte.server.http.RequestInfo in project riposte by Nike-Inc.

the class SignalFxEndpointMetricsHandlerTest method MetricDimensionConfigurator_chainedWith_returns_ChainedMetricDimensionConfigurator_with_correct_args.

@Test
public void MetricDimensionConfigurator_chainedWith_returns_ChainedMetricDimensionConfigurator_with_correct_args() {
    // given
    MetricDimensionConfigurator orig = (rawBuilder, requestInfo, responseInfo, httpState, responseHttpStatusCode, responseHttpStatusCodeXXValue, elapsedTimeMillis, endpoint, endpointClass, method, matchingPathTemplate) -> null;
    MetricDimensionConfigurator chainMe = mock(MetricDimensionConfigurator.class);
    // when
    MetricDimensionConfigurator result = orig.chainedWith(chainMe);
    // then
    assertThat(result).isInstanceOf(ChainedMetricDimensionConfigurator.class);
    ChainedMetricDimensionConfigurator cmdc = (ChainedMetricDimensionConfigurator) result;
    assertThat(cmdc.firstConfigurator).isSameAs(orig);
    assertThat(cmdc.secondConfigurator).isSameAs(chainMe);
}
Also used : MetricDimensionConfigurator(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.MetricDimensionConfigurator) MetricMetadata(com.signalfx.codahale.reporter.MetricMetadata) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ResponseInfo(com.nike.riposte.server.http.ResponseInfo) ServerConfig(com.nike.riposte.server.config.ServerConfig) Reservoir(com.codahale.metrics.Reservoir) DataProviderRunner(com.tngtech.java.junit.dataprovider.DataProviderRunner) DEFAULT_URI_DIMENSION_KEY(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.DefaultMetricDimensionConfigurator.DEFAULT_URI_DIMENSION_KEY) SignalFxReporter(com.signalfx.codahale.reporter.SignalFxReporter) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Matchers.eq(org.mockito.Matchers.eq) Matchers.anyInt(org.mockito.Matchers.anyInt) Mockito.doReturn(org.mockito.Mockito.doReturn) Metric(com.codahale.metrics.Metric) UUID(java.util.UUID) Instant(java.time.Instant) DefaultMetricDimensionConfigurator(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.DefaultMetricDimensionConfigurator) Matchers.any(org.mockito.Matchers.any) SignalFxReporterFactory(com.nike.riposte.metrics.codahale.contrib.SignalFxReporterFactory) RollingWindowTimerBuilder(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.RollingWindowTimerBuilder) Endpoint(com.nike.riposte.server.http.Endpoint) Timer(com.codahale.metrics.Timer) Gauge(com.codahale.metrics.Gauge) Whitebox.getInternalState(org.mockito.internal.util.reflection.Whitebox.getInternalState) BuilderTagger(com.signalfx.codahale.reporter.MetricMetadata.BuilderTagger) SlidingTimeWindowReservoir(com.codahale.metrics.SlidingTimeWindowReservoir) Mockito.mock(org.mockito.Mockito.mock) HttpProcessingState(com.nike.riposte.server.http.HttpProcessingState) Histogram(com.codahale.metrics.Histogram) RequestInfo(com.nike.riposte.server.http.RequestInfo) MetricBuilder(com.signalfx.codahale.metrics.MetricBuilder) RunWith(org.junit.runner.RunWith) DataProvider(com.tngtech.java.junit.dataprovider.DataProvider) Matchers.anyString(org.mockito.Matchers.anyString) Mockito.verifyZeroInteractions(org.mockito.Mockito.verifyZeroInteractions) ChainedMetricDimensionConfigurator(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.ChainedMetricDimensionConfigurator) DEFAULT_METHOD_DIMENSION_KEY(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.DefaultMetricDimensionConfigurator.DEFAULT_METHOD_DIMENSION_KEY) Matchers.anyLong(org.mockito.Matchers.anyLong) Assertions.catchThrowable(org.assertj.core.api.Assertions.catchThrowable) DEFAULT_REQUEST_LATENCY_TIMER_DIMENSION_CONFIGURATOR(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.DEFAULT_REQUEST_LATENCY_TIMER_DIMENSION_CONFIGURATOR) Before(org.junit.Before) DEFAULT_ENDPOINT_CLASS_DIMENSION_KEY(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.DefaultMetricDimensionConfigurator.DEFAULT_ENDPOINT_CLASS_DIMENSION_KEY) DEFAULT_RESPONSE_CODE_DIMENSION_KEY(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.DefaultMetricDimensionConfigurator.DEFAULT_RESPONSE_CODE_DIMENSION_KEY) MetricRegistry(com.codahale.metrics.MetricRegistry) HttpMethod(io.netty.handler.codec.http.HttpMethod) Test(org.junit.Test) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) ChronoUnit(java.time.temporal.ChronoUnit) Pair(com.nike.internal.util.Pair) MetricDimensionConfigurator(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.MetricDimensionConfigurator) DefaultMetricDimensionConfigurator(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.DefaultMetricDimensionConfigurator) ChainedMetricDimensionConfigurator(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.ChainedMetricDimensionConfigurator) ChainedMetricDimensionConfigurator(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.ChainedMetricDimensionConfigurator) Test(org.junit.Test)

Example 33 with RequestInfo

use of com.nike.riposte.server.http.RequestInfo in project riposte by Nike-Inc.

the class RequestInfoSetterHandlerTest method doChannelRead_creates_and_sets_RequestInfo_on_state_and_RequestInfo_is_marked_as_complete_with_all_chunks_if_msg_is_FullHttpRequest.

@Test
public void doChannelRead_creates_and_sets_RequestInfo_on_state_and_RequestInfo_is_marked_as_complete_with_all_chunks_if_msg_is_FullHttpRequest() {
    // given
    FullHttpRequest msgMock = mock(FullHttpRequest.class);
    String uri = "/some/url";
    HttpHeaders headers = new DefaultHttpHeaders();
    doReturn(uri).when(msgMock).getUri();
    doReturn(headers).when(msgMock).headers();
    doReturn(headers).when(msgMock).trailingHeaders();
    doReturn(byteBufMock).when(msgMock).content();
    doReturn(false).when(byteBufMock).isReadable();
    doReturn(HttpVersion.HTTP_1_1).when(msgMock).getProtocolVersion();
    // when
    PipelineContinuationBehavior result = handler.doChannelRead(ctxMock, msgMock);
    // then
    ArgumentCaptor<RequestInfo> requestInfoArgumentCaptor = ArgumentCaptor.forClass(RequestInfo.class);
    verify(stateMock).setRequestInfo(requestInfoArgumentCaptor.capture());
    RequestInfo requestInfo = requestInfoArgumentCaptor.getValue();
    assertThat(requestInfo.getUri()).isEqualTo(uri);
    assertThat(requestInfo.isCompleteRequestWithAllChunks()).isTrue();
    assertThat(result).isEqualTo(PipelineContinuationBehavior.CONTINUE);
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) PipelineContinuationBehavior(com.nike.riposte.server.handler.base.PipelineContinuationBehavior) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) RequestInfo(com.nike.riposte.server.http.RequestInfo) Test(org.junit.Test)

Example 34 with RequestInfo

use of com.nike.riposte.server.http.RequestInfo in project riposte by Nike-Inc.

the class AccessLogEndHandler method doAccessLogging.

protected void doAccessLogging(ChannelHandlerContext ctx) throws Exception {
    if (accessLogger == null)
        return;
    HttpProcessingState httpProcessingState = ChannelAttributes.getHttpProcessingStateForChannel(ctx).get();
    if (httpProcessingState == null) {
        runnableWithTracingAndMdc(() -> logger.warn("HttpProcessingState is null. This shouldn't happen."), ctx).run();
    }
    //      logging for this request, so make sure we only do it if appropriate
    if (httpProcessingState != null && !httpProcessingState.isAccessLogCompletedOrScheduled()) {
        Instant startTime = httpProcessingState.getRequestStartTime();
        ResponseInfo responseInfo = httpProcessingState.getResponseInfo();
        HttpResponse actualResponseObject = httpProcessingState.getActualResponseObject();
        RequestInfo requestInfo = httpProcessingState.getRequestInfo();
        ChannelFutureListener doTheAccessLoggingOperation = new ChannelFutureListenerWithTracingAndMdc((channelFuture) -> accessLogger.log(requestInfo, actualResponseObject, responseInfo, Instant.now().minusMillis(startTime.toEpochMilli()).toEpochMilli()), ctx);
        //      conditions), otherwise do it when the response finishes.
        if (!httpProcessingState.isResponseSendingLastChunkSent())
            doTheAccessLoggingOperation.operationComplete(null);
        else
            httpProcessingState.getResponseWriterFinalChunkChannelFuture().addListener(doTheAccessLoggingOperation);
        httpProcessingState.setAccessLogCompletedOrScheduled(true);
    }
}
Also used : ResponseInfo(com.nike.riposte.server.http.ResponseInfo) HttpProcessingState(com.nike.riposte.server.http.HttpProcessingState) Instant(java.time.Instant) HttpResponse(io.netty.handler.codec.http.HttpResponse) ChannelFutureListenerWithTracingAndMdc(com.nike.riposte.util.asynchelperwrapper.ChannelFutureListenerWithTracingAndMdc) RequestInfo(com.nike.riposte.server.http.RequestInfo) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Example 35 with RequestInfo

use of com.nike.riposte.server.http.RequestInfo in project riposte by Nike-Inc.

the class ChannelPipelineFinalizerHandler method finalizeChannelPipeline.

/**
     * This will first check the given state to see if a response was sent to the user. If not then this method will
     * send a generic error to the user so they get some response (so this method is kind of a backstop in case requests
     * somehow slip through our pipeline without being handled, which should never happen, but we have to have this just
     * in case). Then it will clean out the state so that it is ready for the next request.
     * <p/>
     * If the state indicates that a response was already sent then this method will only clean out the state for the
     * next request and will not send an error.
     */
protected void finalizeChannelPipeline(ChannelHandlerContext ctx, Object msg, HttpProcessingState state, Throwable cause) throws JsonProcessingException {
    RequestInfo<?> requestInfo = exceptionHandlingHandler.getRequestInfo(state, msg);
    //      is sent it will update the state.isResponseSent() so that further calls will return true.
    if (!state.isResponseSendingStarted()) {
        String errorMsg = "Discovered a request that snuck through without a response being sent. This should not " + "be possible and indicates a major problem in the channel pipeline.";
        logger.error(errorMsg, new Exception("Wrapper exception", cause));
        // Send a generic unhandled error response with a wrapper exception so that the logging info output by the
        //      exceptionHandlingHandler will have the overview of what went wrong.
        Exception exceptionToUse = new Exception(errorMsg, cause);
        ResponseInfo<ErrorResponseBody> responseInfo = exceptionHandlingHandler.processUnhandledError(state, msg, exceptionToUse);
        responseSender.sendErrorResponse(ctx, requestInfo, responseInfo);
    }
    ctx.flush();
    //      the metrics for this request, so make sure we only do it if appropriate.
    if (metricsListener != null && !state.isRequestMetricsRecordedOrScheduled()) {
        //      conditions), otherwise do it when the response finishes.
        if (!state.isResponseSendingLastChunkSent()) {
            // TODO: Somehow mark the state as a failed request and update the metrics listener to handle it
            metricsListener.onEvent(ServerMetricsEvent.RESPONSE_SENT, state);
        } else {
            // We need to use a copy of the state in case the original state gets cleaned.
            HttpProcessingState stateCopy = new HttpProcessingState(state);
            stateCopy.getResponseWriterFinalChunkChannelFuture().addListener((ChannelFutureListener) channelFuture -> {
                if (channelFuture.isSuccess())
                    metricsListener.onEvent(ServerMetricsEvent.RESPONSE_SENT, stateCopy);
                else {
                    metricsListener.onEvent(ServerMetricsEvent.RESPONSE_WRITE_FAILED, null);
                }
            });
        }
        state.setRequestMetricsRecordedOrScheduled(true);
    }
    // Make sure to clear out request info chunks, multipart data, and any other resources to prevent reference
    //      counting memory leaks (or any other kind of memory leaks).
    requestInfo.releaseAllResources();
    //      channel if it sits unused longer than the timeout value before the next request arrives.
    if (workerChannelIdleTimeoutMillis > 0 && ctx.pipeline().get(IDLE_CHANNEL_TIMEOUT_HANDLER_NAME) == null) {
        ctx.pipeline().addFirst(IDLE_CHANNEL_TIMEOUT_HANDLER_NAME, new IdleChannelTimeoutHandler(workerChannelIdleTimeoutMillis, "ServerWorkerChannel"));
    }
    //      request is broken. We can't do anything except kill the channel.
    if ((cause != null) && state.isResponseSendingStarted() && !state.isResponseSendingLastChunkSent()) {
        runnableWithTracingAndMdc(() -> logger.error("Received an error in ChannelPipelineFinalizerHandler after response sending was started, but " + "before it finished. Closing the channel. unexpected_error={}", cause.toString()), ctx).run();
        ctx.channel().close();
    }
}
Also used : HttpProcessingState(com.nike.riposte.server.http.HttpProcessingState) Span(com.nike.wingtips.Span) RequestInfo(com.nike.riposte.server.http.RequestInfo) LoggerFactory(org.slf4j.LoggerFactory) ChannelInboundHandler(io.netty.channel.ChannelInboundHandler) ResponseInfo(com.nike.riposte.server.http.ResponseInfo) Tracer(com.nike.wingtips.Tracer) PipelineContinuationBehavior(com.nike.riposte.server.handler.base.PipelineContinuationBehavior) ErrorResponseBody(com.nike.riposte.server.error.handler.ErrorResponseBody) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) ChannelPromise(io.netty.channel.ChannelPromise) MetricsListener(com.nike.riposte.metrics.MetricsListener) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Logger(org.slf4j.Logger) ChannelOutboundHandler(io.netty.channel.ChannelOutboundHandler) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) BaseInboundHandlerWithTracingAndMdcSupport(com.nike.riposte.server.handler.base.BaseInboundHandlerWithTracingAndMdcSupport) IDLE_CHANNEL_TIMEOUT_HANDLER_NAME(com.nike.riposte.server.channelpipeline.HttpChannelInitializer.IDLE_CHANNEL_TIMEOUT_HANDLER_NAME) LastOutboundMessage(com.nike.riposte.server.channelpipeline.message.LastOutboundMessage) ChannelAttributes(com.nike.riposte.server.channelpipeline.ChannelAttributes) AsyncNettyHelper.runnableWithTracingAndMdc(com.nike.riposte.util.AsyncNettyHelper.runnableWithTracingAndMdc) ResponseSender(com.nike.riposte.server.http.ResponseSender) ProxyRouterProcessingState(com.nike.riposte.server.http.ProxyRouterProcessingState) ServerMetricsEvent(com.nike.riposte.server.metrics.ServerMetricsEvent) HttpProcessingState(com.nike.riposte.server.http.HttpProcessingState) ErrorResponseBody(com.nike.riposte.server.error.handler.ErrorResponseBody) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

RequestInfo (com.nike.riposte.server.http.RequestInfo)39 Test (org.junit.Test)30 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)13 HttpProcessingState (com.nike.riposte.server.http.HttpProcessingState)10 ResponseInfo (com.nike.riposte.server.http.ResponseInfo)9 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)6 PipelineContinuationBehavior (com.nike.riposte.server.handler.base.PipelineContinuationBehavior)6 DataProvider (com.tngtech.java.junit.dataprovider.DataProvider)6 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)6 Pair (com.nike.internal.util.Pair)5 RequestInfoForLogging (com.nike.backstopper.handler.RequestInfoForLogging)4 Endpoint (com.nike.riposte.server.http.Endpoint)4 HttpMethod (io.netty.handler.codec.http.HttpMethod)4 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)4 Optional (java.util.Optional)4 Assertions.catchThrowable (org.assertj.core.api.Assertions.catchThrowable)4 LastOutboundMessageSendFullResponseInfo (com.nike.riposte.server.channelpipeline.message.LastOutboundMessageSendFullResponseInfo)3 ChannelAttributes (com.nike.riposte.server.channelpipeline.ChannelAttributes)2 BaseInboundHandlerWithTracingAndMdcSupport (com.nike.riposte.server.handler.base.BaseInboundHandlerWithTracingAndMdcSupport)2 ProxyRouterProcessingState (com.nike.riposte.server.http.ProxyRouterProcessingState)2