aboutsummaryrefslogtreecommitdiffstats
path: root/vid-app-common/src/test/java/org/onap/vid/controller/filter/PromiseRequestIdFilterTest.java
blob: d67bd618c95e99d2d870e5db71c255a7cfce4603 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/*-
 * ============LICENSE_START=======================================================
 * VID
 * ================================================================================
 * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.vid.controller.filter;

import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.emptyOrNullString;
import static org.hamcrest.Matchers.equalToIgnoringCase;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.not;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.onap.portalsdk.core.util.SystemProperties.ECOMP_REQUEST_ID;

import com.google.common.collect.ImmutableMap;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
import org.onap.portalsdk.core.web.support.UserUtils;
import org.onap.vid.logging.RequestIdHeader;
import org.springframework.mock.web.MockHttpServletResponse;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

@Test
public class PromiseRequestIdFilterTest {

    private final String anotherHeader = "ANDREI_RUBLEV";
    private final String anotherValue = "foo value";
    private final String mixedCaseHeader = "x-ecomp-REQUESTID";

    private static final String onapRequestIdHeader = "x-onap-requestid";
    private static final String transactionIdHeader = "x-transactionid";
    private static final String requestIdHeader = "x-requestid";

    private final PromiseRequestIdFilter promiseRequestIdFilter = new PromiseRequestIdFilter();

    @Test
    public void givenRequestIdHeader_headerValueNotChanged() throws IOException, ServletException {

        final String someTxId = "863850e2-8545-4efd-94b8-afba5f52b3d5";

        final ImmutableMap<String, String> incomingRequestHeaders = ImmutableMap.of(
                anotherHeader, anotherValue,
                ECOMP_REQUEST_ID, someTxId
        );

        buildRequestThenRunThroughFilterAndAssertResultRequestHeaders(incomingRequestHeaders, specificTxId(someTxId));
    }


    @Test
    public void givenRequestIdHeaderThatIsNotAUUID_headerValueChanged() throws IOException, ServletException {

        final String someTxId = "863850e28544efd94b8afba5f52b3d5";

        final ImmutableMap<String, String> incomingRequestHeaders = ImmutableMap.of(
                anotherHeader, anotherValue,
                ECOMP_REQUEST_ID, someTxId
        );

        buildRequestThenRunThroughFilterAndAssertResultRequestHeaders(incomingRequestHeaders, UserUtils::getRequestId);
    }


    @Test
    public void givenMixedCaseRequestIdHeader_headerValueNotChanged() throws IOException, ServletException {

        final String someTxId = "729bbd8d-b0c2-4809-a794-dcccd9cda2c0";

        final ImmutableMap<String, String> incomingRequestHeaders = ImmutableMap.of(
                mixedCaseHeader, someTxId,
                anotherHeader, anotherValue
        );

        buildRequestThenRunThroughFilterAndAssertResultRequestHeaders(incomingRequestHeaders, specificTxId(someTxId));
    }

    @Test
    public void givenNoRequestIdHeader_headerValueWasGenerated() throws IOException, ServletException {

        final ImmutableMap<String, String> incomingRequestHeaders = ImmutableMap.of(
                anotherHeader, anotherValue
        );

        buildRequestThenRunThroughFilterAndAssertResultRequestHeaders(incomingRequestHeaders, UserUtils::getRequestId);
    }

    @Test
    public void givenTwoRequestIdHeader_onapHeaderValueIsUsed() throws IOException, ServletException {

        final String onapTxId = "863850e2-8545-4efd-94b8-AFBA5F52B3D5"; // note mixed case
        final String ecompTxId = "6e8ff89e-88a4-4977-b63f-3142892b6e08";

        final ImmutableMap<String, String> incomingRequestHeaders = ImmutableMap.of(
            anotherHeader, anotherValue,
            ECOMP_REQUEST_ID, ecompTxId,
            onapRequestIdHeader, onapTxId
        );

        buildRequestThenRunThroughFilterAndAssertResultRequestHeaders(incomingRequestHeaders, specificTxId(onapTxId));
    }

    @Test
    public void givenTwoRequestIdHeaderAndHigherPriorityIsMalformed_headerValueIsGenerated() throws IOException, ServletException {

        final String malformedTxId = "6e8ff89e-88a4-4977-b63f-3142892b6e08-";
        final String anotherTxId = "863850e2-8545-4efd-94b8-afba5f52b3d5";

        final ImmutableMap<String, String> incomingRequestHeaders = ImmutableMap.of(
            anotherHeader, anotherValue,
            requestIdHeader, malformedTxId, // requestIdHeader as higher priority than transactionIdHeader
            transactionIdHeader, anotherTxId
        );

        HttpServletRequest wrappedRequest =
            buildRequestThenRunThroughFilterAndAssertResultRequestHeaders(incomingRequestHeaders, UserUtils::getRequestId);

        assertThat(UserUtils.getRequestId(wrappedRequest),
            not(anyOf(equalTo(malformedTxId), equalTo(anotherTxId)))
        );
    }


    @Test
    public void toUuidOrElse_givenValid_yieldSame() {
        final String someTxId = "729bbd8d-b0c2-4809-a794-DCCCD9CDA2C0"; // note mixed case
        UUID unexpected = UUID.randomUUID();
        assertThat(promiseRequestIdFilter.toUuidOrElse(someTxId, () -> unexpected), is(UUID.fromString(someTxId)));
    }

    @Test
    public void toUuidOrElse_givenNull_yieldSupplier() {
        UUID expected = UUID.fromString("729bbd8d-b0c2-4809-a794-dcccd9cda2c0");
        assertThat(promiseRequestIdFilter.toUuidOrElse(null, () -> expected), is(expected));
    }

    @Test
    public void toUuidOrElse_givenMalformed_yieldSupplier() {
        UUID expected = UUID.fromString("729bbd8d-b0c2-4809-a794-dcccd9cda2c0");
        assertThat(promiseRequestIdFilter.toUuidOrElse("malformed uuid", () -> expected), is(expected));
    }

    @DataProvider
    public static Object[][] severalRequestIdHeaders() {
        String someTxId = "69fa2575-d7f2-482c-ad1b-53a63ca03617";
        String anotherTxId = "06de373b-7e19-4357-9bd1-ed95682ae3a4";

        return new Object[][]{
            {
                "header is selected when single", RequestIdHeader.TRANSACTION_ID,
                ImmutableMap.of(
                    transactionIdHeader, someTxId
                )
            }, {
                "header is selected when first", RequestIdHeader.ONAP_ID,
                ImmutableMap.of(
                    onapRequestIdHeader, someTxId,
                    "noise-header", anotherTxId,
                    ECOMP_REQUEST_ID, anotherTxId
                )
            }, {
                "header is selected when last", RequestIdHeader.ONAP_ID,
                ImmutableMap.of(
                    ECOMP_REQUEST_ID, anotherTxId,
                    "noise-header", anotherTxId,
                    onapRequestIdHeader, someTxId
                )
            }, {
                "header is selected when value is invalid uuid", RequestIdHeader.ONAP_ID,
                ImmutableMap.of(
                    onapRequestIdHeader, "invalid-uuid"
                )
            }, {
                "header is selected when no ecomp-request-id", RequestIdHeader.ONAP_ID,
                ImmutableMap.of(
                    requestIdHeader, anotherTxId,
                    onapRequestIdHeader, someTxId
                )
            }, {
                "ECOMP_REQUEST_ID is returned when no request-id header", RequestIdHeader.ECOMP_ID,
                ImmutableMap.of(
                    "tsamina-mina", anotherTxId,
                    "waka-waka", anotherTxId
                )
            },
        };
    }

    @Test(dataProvider = "severalRequestIdHeaders")
    public void highestPriorityHeader_givenSeveralRequestIdHeaders_correctHeaderIsUsed(String description, RequestIdHeader expectedHeader, Map<String, String> incomingRequestHeaders) {

        HttpServletRequest mockedHttpServletRequest = createMockedHttpServletRequest(incomingRequestHeaders);

        assertThat(description,
            promiseRequestIdFilter.highestPriorityHeader(mockedHttpServletRequest), is(expectedHeader));
    }


    private HttpServletRequest buildRequestThenRunThroughFilterAndAssertResultRequestHeaders(
            ImmutableMap<String, String> originalRequestHeaders,
            Function<HttpServletRequest, String> txIdExtractor
    ) throws IOException, ServletException {
        HttpServletRequest servletRequest = createMockedHttpServletRequest(originalRequestHeaders);
        HttpServletResponse servletResponse = createMockedHttpServletResponse();

        final FilterChain capturingFilterChain = Mockito.mock(FilterChain.class);

        //////////////////
        //
        // doFilter() is the function under test
        //
        promiseRequestIdFilter.doFilter(servletRequest, servletResponse, capturingFilterChain);
        //
        //////////////////

        final ServletRequest capturedServletRequest = extractCapturedServletRequest(capturingFilterChain);
        final ServletResponse capturedServletResponse = extractCapturedServletResponse(capturingFilterChain);
        final String expectedTxId = txIdExtractor.apply((HttpServletRequest) capturedServletRequest);

        assertRequestObjectHeaders(capturedServletRequest, expectedTxId);
        assertResponseObjectHeaders(capturedServletResponse, expectedTxId);

        return (HttpServletRequest) capturedServletRequest;
    }


    private void assertRequestObjectHeaders(ServletRequest request, String expectedTxId) {
        /*
        Assert that:
        - Two headers are in place
        - Direct value extraction is as expected
        - UserUtils.getRequestId() returns correct and valid value
         */
        final HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        assertThat(Collections.list(httpServletRequest.getHeaderNames()),
                hasItems(equalToIgnoringCase(ECOMP_REQUEST_ID), equalToIgnoringCase(anotherHeader)));

        assertThat(httpServletRequest.getHeader(anotherHeader), is(anotherValue));

        assertThat(httpServletRequest.getHeader(ECOMP_REQUEST_ID), equalToIgnoringCase(expectedTxId));
        assertThat(httpServletRequest.getHeader(mixedCaseHeader), equalToIgnoringCase(expectedTxId));

        assertThat(UserUtils.getRequestId(httpServletRequest), equalToIgnoringCase(expectedTxId));
        assertThat(UserUtils.getRequestId(httpServletRequest), is(not(emptyOrNullString())));
    }

    private void assertResponseObjectHeaders(ServletResponse response, String txId) {
        final String REQUEST_ID_HEADER_NAME_IN_RESPONSE = mixedCaseHeader + "-echo";
        final HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        assertThat("header " + REQUEST_ID_HEADER_NAME_IN_RESPONSE.toLowerCase() + " in response must be provided",
                httpServletResponse.getHeader(REQUEST_ID_HEADER_NAME_IN_RESPONSE), equalToIgnoringCase(txId));
    }



    private HttpServletRequest createMockedHttpServletRequest(Map<String, String> requestHeaders) {
        HttpServletRequest servletRequest = Mockito.mock(HttpServletRequest.class);
        requestHeaders.forEach((k, v) -> {
            Mockito.when(servletRequest.getHeader(argThat(s -> equalsIgnoreCase(s, k)))).thenReturn(v);
            Mockito.when(servletRequest.getHeaders(argThat(s -> equalsIgnoreCase(s, k)))).then(returnEnumerationAnswer(v));
        });
        Mockito.when(servletRequest.getHeaderNames()).then(returnEnumerationAnswer(requestHeaders.keySet()));
        return servletRequest;
    }

    private HttpServletResponse createMockedHttpServletResponse() {
        return new MockHttpServletResponse();
    }

    private static Answer<Enumeration<String>> returnEnumerationAnswer(String ... items) {
        return returnEnumerationAnswer(Arrays.asList(items));
    }

    private static Answer<Enumeration<String>> returnEnumerationAnswer(Collection<String> items) {
        return invocation -> Collections.enumeration(items);
    }

    private Function<HttpServletRequest, String> specificTxId(String someTxId) {
        return r -> someTxId;
    }

    private ServletRequest extractCapturedServletRequest(FilterChain capturingFilterChain) throws IOException, ServletException {
        ArgumentCaptor<ServletRequest> captor = ArgumentCaptor.forClass(ServletRequest.class);
        Mockito.verify(capturingFilterChain).doFilter(captor.capture(), any());
        return captor.getValue();
    }

    private ServletResponse extractCapturedServletResponse(FilterChain capturingFilterChain) throws IOException, ServletException {
        ArgumentCaptor<ServletResponse> captor = ArgumentCaptor.forClass(ServletResponse.class);
        Mockito.verify(capturingFilterChain).doFilter(any(), captor.capture());
        return captor.getValue();
    }

}