Merge "ICS tests with istio and JWTs"
[nonrtric.git] / dmaap-adaptor-java / src / test / java / org / oran / dmaapadapter / IntegrationWithIcs.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2021 Nordix Foundation
6  * %%
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20
21 package org.oran.dmaapadapter;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.awaitility.Awaitility.await;
25
26 import com.google.gson.Gson;
27 import com.google.gson.GsonBuilder;
28 import com.google.gson.JsonParser;
29
30 import org.junit.jupiter.api.AfterEach;
31 import org.junit.jupiter.api.Test;
32 import org.junit.jupiter.api.extension.ExtendWith;
33 import org.oran.dmaapadapter.clients.AsyncRestClient;
34 import org.oran.dmaapadapter.clients.AsyncRestClientFactory;
35 import org.oran.dmaapadapter.configuration.ApplicationConfig;
36 import org.oran.dmaapadapter.configuration.ImmutableHttpProxyConfig;
37 import org.oran.dmaapadapter.configuration.ImmutableWebClientConfig;
38 import org.oran.dmaapadapter.configuration.WebClientConfig;
39 import org.oran.dmaapadapter.configuration.WebClientConfig.HttpProxyConfig;
40 import org.oran.dmaapadapter.r1.ConsumerJobInfo;
41 import org.oran.dmaapadapter.repository.InfoTypes;
42 import org.oran.dmaapadapter.repository.Job;
43 import org.oran.dmaapadapter.repository.Jobs;
44 import org.oran.dmaapadapter.tasks.ProducerRegstrationTask;
45 import org.springframework.beans.factory.annotation.Autowired;
46 import org.springframework.boot.test.context.SpringBootTest;
47 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
48 import org.springframework.boot.test.context.TestConfiguration;
49 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
50 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
51 import org.springframework.context.annotation.Bean;
52 import org.springframework.http.HttpStatus;
53 import org.springframework.test.context.TestPropertySource;
54 import org.springframework.test.context.junit.jupiter.SpringExtension;
55
56
57 @SuppressWarnings("java:S3577") // Rename class
58 @ExtendWith(SpringExtension.class)
59 @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
60 @TestPropertySource(properties = { //
61         "server.ssl.key-store=./config/keystore.jks", //
62         "app.webclient.trust-store=./config/truststore.jks", //
63         "app.configuration-filepath=./src/test/resources/test_application_configuration.json", //
64         "app.ics-base-url=https://localhost:8434" //
65 })
66 class IntegrationWithIcs {
67
68     private static final String DMAAP_JOB_ID = "DMAAP_JOB_ID";
69     private static final String DMAAP_TYPE_ID = "DmaapInformationType";
70
71     @Autowired
72     private ApplicationConfig applicationConfig;
73
74     @Autowired
75     private ProducerRegstrationTask producerRegstrationTask;
76
77     @Autowired
78     private Jobs jobs;
79
80     @Autowired
81     private InfoTypes types;
82
83     @Autowired
84     private ConsumerController consumerController;
85
86     private static Gson gson = new GsonBuilder().create();
87
88     static class TestApplicationConfig extends ApplicationConfig {
89
90         @Override
91         public String getIcsBaseUrl() {
92             return "https://localhost:8434";
93         }
94
95         @Override
96         public String getDmaapBaseUrl() {
97             return thisProcessUrl();
98         }
99
100         @Override
101         public String getSelfUrl() {
102             return thisProcessUrl();
103         }
104
105         private String thisProcessUrl() {
106             final String url = "https://localhost:" + getLocalServerHttpPort();
107             return url;
108         }
109     }
110
111     /**
112      * Overrides the BeanFactory.
113      */
114     @TestConfiguration
115     static class TestBeanFactory extends BeanFactory {
116
117         @Override
118         @Bean
119         public ServletWebServerFactory servletContainer() {
120             return new TomcatServletWebServerFactory();
121         }
122
123         @Override
124         @Bean
125         public ApplicationConfig getApplicationConfig() {
126             TestApplicationConfig cfg = new TestApplicationConfig();
127             return cfg;
128         }
129     }
130
131     @AfterEach
132     void reset() {
133         this.consumerController.testResults.reset();
134         assertThat(this.jobs.size()).isZero();
135     }
136
137     private AsyncRestClient restClient(boolean useTrustValidation) {
138         WebClientConfig config = this.applicationConfig.getWebClientConfig();
139         HttpProxyConfig httpProxyConfig = ImmutableHttpProxyConfig.builder() //
140                 .httpProxyHost("") //
141                 .httpProxyPort(0) //
142                 .build();
143         config = ImmutableWebClientConfig.builder() //
144                 .keyStoreType(config.keyStoreType()) //
145                 .keyStorePassword(config.keyStorePassword()) //
146                 .keyStore(config.keyStore()) //
147                 .keyPassword(config.keyPassword()) //
148                 .isTrustStoreUsed(useTrustValidation) //
149                 .trustStore(config.trustStore()) //
150                 .trustStorePassword(config.trustStorePassword()) //
151                 .httpProxyConfig(httpProxyConfig).build();
152
153         AsyncRestClientFactory restClientFactory = new AsyncRestClientFactory(config);
154         return restClientFactory.createRestClientNoHttpProxy(selfBaseUrl());
155     }
156
157     private AsyncRestClient restClient() {
158         return restClient(false);
159     }
160
161     private String selfBaseUrl() {
162         return "https://localhost:" + this.applicationConfig.getLocalServerHttpPort();
163     }
164
165     private String icsBaseUrl() {
166         return applicationConfig.getIcsBaseUrl();
167     }
168
169     private String jobUrl(String jobId) {
170         return icsBaseUrl() + "/data-consumer/v1/info-jobs/" + jobId + "?typeCheck=true";
171     }
172
173     private void createInformationJobInIcs(String typeId, String jobId, String filter) {
174         String body = gson.toJson(consumerJobInfo(typeId, filter));
175         try {
176             // Delete the job if it already exists
177             deleteInformationJobInIcs(jobId);
178         } catch (Exception e) {
179         }
180         restClient().putForEntity(jobUrl(jobId), body).block();
181     }
182
183     private void deleteInformationJobInIcs(String jobId) {
184         restClient().delete(jobUrl(jobId)).block();
185     }
186
187     private ConsumerJobInfo consumerJobInfo(String typeId, String filter) {
188         return consumerJobInfo(typeId, DMAAP_JOB_ID, filter);
189     }
190
191     private Object jsonObject(String json) {
192         try {
193             return JsonParser.parseString(json).getAsJsonObject();
194         } catch (Exception e) {
195             throw new NullPointerException(e.toString());
196         }
197     }
198
199     private String quote(String str) {
200         return "\"" + str + "\"";
201     }
202
203     private String consumerUri() {
204         return selfBaseUrl() + ConsumerController.CONSUMER_TARGET_URL;
205     }
206
207     private ConsumerJobInfo consumerJobInfo(String typeId, String infoJobId, String filter) {
208         try {
209
210             String jsonStr = "{ \"filter\" :" + quote(filter) + "}";
211             return new ConsumerJobInfo(typeId, jsonObject(jsonStr), "owner", consumerUri(), "");
212         } catch (Exception e) {
213             return null;
214         }
215     }
216
217     @Test
218     void testCreateKafkaJob() {
219         await().untilAsserted(() -> assertThat(producerRegstrationTask.isRegisteredInIcs()).isTrue());
220         final String TYPE_ID = "KafkaInformationType";
221
222         Job.Parameters param = new Job.Parameters("filter", new Job.BufferTimeout(123, 456), 1);
223
224         ConsumerJobInfo jobInfo =
225                 new ConsumerJobInfo(TYPE_ID, jsonObject(gson.toJson(param)), "owner", consumerUri(), "");
226         String body = gson.toJson(jobInfo);
227
228         restClient().putForEntity(jobUrl("KAFKA_JOB_ID"), body).block();
229
230         await().untilAsserted(() -> assertThat(this.jobs.size()).isEqualTo(1));
231
232         deleteInformationJobInIcs("KAFKA_JOB_ID");
233         await().untilAsserted(() -> assertThat(this.jobs.size()).isZero());
234     }
235
236     @Test
237     void testKafkaJobParameterOutOfRange() {
238         await().untilAsserted(() -> assertThat(producerRegstrationTask.isRegisteredInIcs()).isTrue());
239         final String TYPE_ID = "KafkaInformationType";
240
241         Job.Parameters param = new Job.Parameters("filter", new Job.BufferTimeout(123, 170 * 1000), 1);
242
243         ConsumerJobInfo jobInfo =
244                 new ConsumerJobInfo(TYPE_ID, jsonObject(gson.toJson(param)), "owner", consumerUri(), "");
245         String body = gson.toJson(jobInfo);
246
247         ApplicationTest.testErrorCode(restClient().put(jobUrl("KAFKA_JOB_ID"), body), HttpStatus.BAD_REQUEST,
248                 "Json validation failure");
249
250     }
251
252     @Test
253     void testDmaapMessage() throws Exception {
254         await().untilAsserted(() -> assertThat(producerRegstrationTask.isRegisteredInIcs()).isTrue());
255
256         createInformationJobInIcs(DMAAP_TYPE_ID, DMAAP_JOB_ID, ".*DmaapResponse.*");
257
258         await().untilAsserted(() -> assertThat(this.jobs.size()).isEqualTo(1));
259
260         DmaapSimulatorController.dmaapResponses.add("DmaapResponse1");
261         DmaapSimulatorController.dmaapResponses.add("DmaapResponse2");
262         DmaapSimulatorController.dmaapResponses.add("Junk");
263
264         ConsumerController.TestResults results = this.consumerController.testResults;
265         await().untilAsserted(() -> assertThat(results.receivedBodies.size()).isEqualTo(2));
266         assertThat(results.receivedBodies.get(0)).isEqualTo("DmaapResponse1");
267
268         deleteInformationJobInIcs(DMAAP_JOB_ID);
269
270         await().untilAsserted(() -> assertThat(this.jobs.size()).isZero());
271     }
272
273 }