2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2024-2025 OpenInfra Foundation Europe. All rights reserved.
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.cps.ncmp.impl.data.policyexecutor
23 import com.fasterxml.jackson.core.JsonProcessingException;
24 import ch.qos.logback.classic.Level
25 import ch.qos.logback.classic.Logger
26 import ch.qos.logback.classic.spi.ILoggingEvent
27 import ch.qos.logback.core.read.ListAppender
28 import com.fasterxml.jackson.databind.JsonNode
29 import com.fasterxml.jackson.databind.ObjectMapper
30 import org.onap.cps.ncmp.api.exceptions.NcmpException
31 import org.onap.cps.ncmp.api.exceptions.PolicyExecutorException
32 import org.onap.cps.ncmp.impl.inventory.models.YangModelCmHandle
33 import org.onap.cps.ncmp.impl.provmns.RequestPathParameters
34 import org.onap.cps.ncmp.impl.provmns.model.ResourceOneOf
35 import org.onap.cps.utils.JsonObjectMapper
36 import org.slf4j.LoggerFactory
37 import org.springframework.http.HttpStatus
38 import org.springframework.http.ResponseEntity
39 import org.springframework.web.reactive.function.client.WebClient
40 import org.springframework.web.reactive.function.client.WebClientRequestException
41 import org.springframework.web.reactive.function.client.WebClientResponseException
42 import reactor.core.publisher.Mono
43 import spock.lang.Specification
44 import java.util.concurrent.TimeoutException
46 import static org.onap.cps.ncmp.api.data.models.OperationType.CREATE
47 import static org.onap.cps.ncmp.api.data.models.OperationType.DELETE
48 import static org.onap.cps.ncmp.api.data.models.OperationType.PATCH
49 import static org.onap.cps.ncmp.api.data.models.OperationType.UPDATE
51 class PolicyExecutorSpec extends Specification {
53 def mockWebClient = Mock(WebClient)
54 def mockRequestBodyUriSpec = Mock(WebClient.RequestBodyUriSpec)
55 def mockResponseSpec = Mock(WebClient.ResponseSpec)
56 def spiedObjectMapper = Spy(ObjectMapper)
57 def jsonObjectMapper = new JsonObjectMapper(spiedObjectMapper)
59 PolicyExecutor objectUnderTest = new PolicyExecutor(mockWebClient, spiedObjectMapper,jsonObjectMapper)
61 def logAppender = Spy(ListAppender<ILoggingEvent>)
63 def someValidJson = '{"Hello":"World"}'
67 objectUnderTest.enabled = true
68 objectUnderTest.serverAddress = 'some host'
69 objectUnderTest.serverPort = 'some port'
70 mockWebClient.post() >> mockRequestBodyUriSpec
71 mockRequestBodyUriSpec.uri(*_) >> mockRequestBodyUriSpec
72 mockRequestBodyUriSpec.header(*_) >> mockRequestBodyUriSpec
73 mockRequestBodyUriSpec.body(*_) >> mockRequestBodyUriSpec
74 mockRequestBodyUriSpec.retrieve() >> mockResponseSpec
78 ((Logger) LoggerFactory.getLogger(PolicyExecutor)).detachAndStopAllAppenders()
81 def 'Permission check with "allow" decision.'() {
82 given: 'allow response'
83 mockResponse([permissionResult:'allow'], HttpStatus.OK)
84 when: 'permission is checked for an operation'
85 objectUnderTest.checkPermission(new YangModelCmHandle(), operationType, 'my credentials','my resource',someValidJson)
86 then: 'system logs the operation is allowed'
87 assert getLogEntry(4) == 'Operation allowed.'
88 and: 'no exception occurs'
90 where: 'all write operations are tested'
91 operationType << [ CREATE, DELETE, PATCH, UPDATE ]
94 def 'Permission check with "other" decision (not allowed).'() {
95 given: 'other response'
96 mockResponse([permissionResult:'other', id:123, message:'I dont like Mondays' ], HttpStatus.OK)
97 when: 'permission is checked for an operation'
98 objectUnderTest.checkPermission(new YangModelCmHandle(), PATCH, 'my credentials','my resource',someValidJson)
99 then: 'Policy Executor exception is thrown'
100 def thrownException = thrown(PolicyExecutorException)
101 assert thrownException.message == 'Operation not allowed. Decision id 123 : other'
102 assert thrownException.details == 'I dont like Mondays'
105 def 'Permission check with non-2xx response and "allow" default decision.'() {
106 given: 'non-2xx http response'
108 and: 'the configured default decision is "allow"'
109 objectUnderTest.defaultDecision = 'allow'
110 when: 'permission is checked for an operation'
111 objectUnderTest.checkPermission(new YangModelCmHandle(), PATCH, 'my credentials','my resource',someValidJson)
112 then: 'No exception is thrown'
116 def 'Permission check with non-2xx response and "other" default decision.'() {
117 given: 'non-2xx http response'
118 def webClientException = mockErrorResponse()
119 and: 'the configured default decision is NOT "allow"'
120 objectUnderTest.defaultDecision = 'deny by default'
121 when: 'permission is checked for an operation'
122 objectUnderTest.checkPermission(new YangModelCmHandle(), PATCH, 'my credentials', 'my resource', someValidJson)
123 then: 'Policy Executor exception is thrown'
124 def thrownException = thrown(PolicyExecutorException)
125 assert thrownException.message == 'Operation not allowed. Decision id N/A : deny by default'
126 assert thrownException.details == 'Policy Executor returned HTTP Status code 418. Falling back to configured default decision: deny by default'
127 and: 'the cause is the original web client exception'
128 assert thrownException.cause == webClientException
131 def 'Permission check with invalid response from Policy Executor.'() {
132 given: 'invalid response from Policy executor'
133 mockResponseSpec.toEntity(*_) >> Mono.just(new ResponseEntity<>(null, HttpStatus.OK))
134 when: 'permission is checked for an operation'
135 objectUnderTest.checkPermission(new YangModelCmHandle(), CREATE, 'my credentials', 'my resource', someValidJson)
136 then: 'system logs the expected message'
137 assert getLogEntry(3) == 'No valid response body from Policy Executor, ignored'
140 def 'Permission check with timeout exception.'() {
141 given: 'a timeout during the request'
142 def timeoutException = new TimeoutException()
143 mockResponseSpec.toEntity(*_) >> { throw new RuntimeException(timeoutException) }
144 and: 'the configured default decision is NOT "allow"'
145 objectUnderTest.defaultDecision = 'deny by default'
146 when: 'permission is checked for an operation'
147 objectUnderTest.checkPermission(new YangModelCmHandle(), CREATE, 'my credentials', 'my resource', someValidJson)
148 then: 'Policy Executor exception is thrown'
149 def thrownException = thrown(PolicyExecutorException)
150 assert thrownException.message == 'Operation not allowed. Decision id N/A : deny by default'
151 assert thrownException.details == 'Policy Executor request timed out. Falling back to configured default decision: deny by default'
152 and: 'the cause is the original time out exception'
153 assert thrownException.cause == timeoutException
156 def 'Permission check with unknown host.'() {
157 given: 'a unknown host exception during the request'
158 def unknownHostException = new UnknownHostException()
159 mockResponseSpec.toEntity(*_) >> { throw new RuntimeException(unknownHostException) }
160 and: 'the configured default decision is NOT "allow"'
161 objectUnderTest.defaultDecision = 'deny by default'
162 when: 'permission is checked for an operation'
163 objectUnderTest.checkPermission(new YangModelCmHandle(), CREATE, 'my credentials', 'my resource', someValidJson)
164 then: 'Policy Executor exception is thrown'
165 def thrownException = thrown(PolicyExecutorException)
166 assert thrownException.message == 'Operation not allowed. Decision id N/A : deny by default'
167 assert thrownException.details == 'Unexpected error during Policy Executor call. Falling back to configured default decision: deny by default'
168 and: 'the cause is the original unknown host exception'
169 assert thrownException.cause == unknownHostException
172 def 'Permission check with #scenario exception and default decision "allow".'() {
173 given: 'a #scenario exception during the request'
174 mockResponseSpec.toEntity(*_) >> { throw new RuntimeException(cause)}
175 and: 'the configured default decision is "allow"'
176 objectUnderTest.defaultDecision = 'allow'
177 when: 'permission is checked for an operation'
178 objectUnderTest.checkPermission(new YangModelCmHandle(), CREATE, 'my credentials', 'my resource', someValidJson)
179 then: 'no exception is thrown'
181 where: 'the following exceptions are thrown during the request'
183 'timeout' | new TimeoutException()
184 'unknown host' | new UnknownHostException()
187 def 'Permission check with other runtime exception.'() {
188 given: 'some other runtime exception'
189 def originalException = new RuntimeException()
190 mockResponseSpec.toEntity(*_) >> { throw originalException}
191 when: 'permission is checked for an operation'
192 objectUnderTest.checkPermission(new YangModelCmHandle(), CREATE, 'my credentials', 'my resource', someValidJson)
193 then: 'The original exception is thrown'
194 def thrownException = thrown(RuntimeException)
195 assert thrownException == originalException
198 def 'Permission check with an invalid change request json.'() {
199 when: 'permission is checked for an invalid change request'
200 objectUnderTest.checkPermission(new YangModelCmHandle(), CREATE, 'my credentials', 'my resource', 'invalid json string')
201 then: 'an ncmp exception thrown'
202 def ncmpException = thrown(NcmpException)
203 ncmpException.message == 'Cannot convert Change Request data to Object'
204 ncmpException.details.contains('invalid json string')
207 def 'Permission check feature disabled.'() {
208 given: 'feature is disabled'
209 objectUnderTest.enabled = false
210 when: 'permission is checked for an operation'
211 objectUnderTest.checkPermission(new YangModelCmHandle(), PATCH, 'my credentials','my resource',someValidJson)
212 then: 'system logs that the feature not enabled'
213 assert getLogEntry(0) == 'Policy Executor Enabled: false'
216 def 'Permission check with web client request exception.'() {
217 given: 'a WebClientRequestException is thrown during the Policy Executor call'
218 def webClientRequestException = Mock(WebClientRequestException)
219 webClientRequestException.getMessage() >> "some error message"
220 mockResponseSpec.toEntity(*_) >> { throw webClientRequestException }
221 objectUnderTest.defaultDecision = 'deny'
222 when: 'permission is checked for a write operation'
223 objectUnderTest.checkPermission(new YangModelCmHandle(), CREATE, 'my credentials', 'my resource', someValidJson)
224 then: 'a PolicyExecutorException is thrown with the expected fallback message'
225 def thrownException = thrown(PolicyExecutorException)
226 thrownException.message == 'Operation not allowed. Decision id N/A : deny'
227 thrownException.details == 'Network or I/O error while attempting to contact Policy Executor. Falling back to configured default decision: deny'
228 thrownException.cause == webClientRequestException
231 def 'Build policy executor operation details from ProvMnS request parameters where #scenario.'() {
232 given: 'a provMnsRequestParameter and a resource'
233 def path = new RequestPathParameters(uriLdnFirstPart: 'someUriLdnFirstPart', className: 'someClassName', id: 'someId')
234 def resource = new ResourceOneOf(id: 'someResourceId', attributes: ['someAttribute1:someValue1', 'someAttribute2:someValue2'], objectClass: objectClass)
235 when: 'a configurationManagementOperation is created and converted to JSON'
236 def result = objectUnderTest.buildOperationDetails(CREATE, path, resource)
237 then: 'the result is as expected (using json to compare)'
238 String expectedJsonString = '{"operation":"CREATE","targetIdentifier":"someUriLdnFirstPart/someClassName=someId","changeRequest":{"' + changeRequestClassReference + '":[{"id":"someId","attributes":["someAttribute1:someValue1","someAttribute2:someValue2"]}]}}'
239 assert jsonObjectMapper.asJsonString(result) == expectedJsonString
241 scenario | objectClass || changeRequestClassReference
242 'objectClass is populated' | 'someObjectClass' || 'someObjectClass'
243 'objectClass is empty' | '' || 'someClassName'
244 'objectClass is null' | null || 'someClassName'
247 def 'Build Policy Executor Operation Details with a exception during conversion'() {
248 given: 'a provMnsRequestParameter and a resource'
249 def path = new RequestPathParameters(uriLdnFirstPart: 'someUriLdnFirstPart', className: 'someClassName', id: 'someId')
250 def resource = new ResourceOneOf(id: 'someResourceId', attributes: ['someAttribute1:someValue1', 'someAttribute2:someValue2'])
251 and: 'json object mapper throws an exception'
252 def originalException = new JsonProcessingException('some-exception')
253 spiedObjectMapper.readValue(*_) >> {throw originalException}
254 when: 'a configurationManagementOperation is created and converted to JSON'
255 objectUnderTest.buildOperationDetails(CREATE, path, resource)
256 then: 'the expected exception is throw and matches the original'
260 def mockResponse(mockResponseAsMap, httpStatus) {
261 JsonNode jsonNode = spiedObjectMapper.readTree(spiedObjectMapper.writeValueAsString(mockResponseAsMap))
262 def mono = Mono.just(new ResponseEntity<>(jsonNode, httpStatus))
263 mockResponseSpec.toEntity(*_) >> mono
266 def mockErrorResponse() {
267 def webClientResponseException = Mock(WebClientResponseException)
268 webClientResponseException.getStatusCode() >> HttpStatus.I_AM_A_TEAPOT
269 mockResponseSpec.toEntity(*_) >> { throw webClientResponseException }
270 return webClientResponseException
274 def logger = LoggerFactory.getLogger(PolicyExecutor)
275 logger.setLevel(Level.TRACE)
276 logger.addAppender(logAppender)
280 def getLogEntry(index) {
281 logAppender.list[index].formattedMessage