ea5b5a1402fac41533b63c64d84cef68f8ad648b
[cps.git] /
1 /*
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
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.policyexecutor.stub.controller;
22
23 import java.util.Locale;
24 import java.util.regex.Matcher;
25 import java.util.regex.Pattern;
26 import lombok.RequiredArgsConstructor;
27 import lombok.extern.slf4j.Slf4j;
28 import org.onap.cps.policyexecutor.stub.api.OperationPermissionApi;
29 import org.onap.cps.policyexecutor.stub.model.Operation;
30 import org.onap.cps.policyexecutor.stub.model.PermissionRequest;
31 import org.onap.cps.policyexecutor.stub.model.PermissionResponse;
32 import org.springframework.http.HttpStatus;
33 import org.springframework.http.HttpStatusCode;
34 import org.springframework.http.ResponseEntity;
35 import org.springframework.web.bind.annotation.RequestMapping;
36 import org.springframework.web.bind.annotation.RestController;
37
38 @RestController
39 @RequestMapping("/operation-permission/v1")
40 @RequiredArgsConstructor
41 @Slf4j
42 public class PolicyExecutorStubController implements OperationPermissionApi {
43
44     private final Sleeper sleeper;
45     private static final Pattern ERROR_CODE_PATTERN = Pattern.compile("(\\d{3})");
46     private int decisionCounter = 0;
47     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
48     // Do NOT change below to final as it needs to be set during test
49     private static int slowResponseTimeInSeconds = 40;
50
51     @Override
52     public ResponseEntity<PermissionResponse> initiatePermissionRequest(final String contentType,
53                                                                         final PermissionRequest permissionRequest,
54                                                                         final String accept,
55                                                                         final String authorization) {
56         log.info("Stub Policy Executor Invoked");
57         if (permissionRequest.getOperations().isEmpty()) {
58             return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
59         }
60         final Operation firstOperation = permissionRequest.getOperations().iterator().next();
61         log.info("1st Operation: {}", firstOperation.getOperation());
62         if (!"delete".equals(firstOperation.getOperation()) && firstOperation.getChangeRequest() == null) {
63             log.warn("Change Request is required for {} operations", firstOperation.getOperation());
64             return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
65         }
66         return handleOperation(firstOperation);
67     }
68
69     private ResponseEntity<PermissionResponse> handleOperation(final Operation operation) {
70         final String targetIdentifier = operation.getTargetIdentifier();
71
72         final Matcher matcher = ERROR_CODE_PATTERN.matcher(targetIdentifier);
73         if (matcher.find()) {
74             final int errorCode = Integer.parseInt(matcher.group(1));
75             log.warn("Stub is mocking an error response, code: {}", errorCode);
76             return new ResponseEntity<>(HttpStatusCode.valueOf(errorCode));
77         }
78
79         return createPolicyExecutionResponse(targetIdentifier);
80     }
81
82     private ResponseEntity<PermissionResponse> createPolicyExecutionResponse(final String targetIdentifier) {
83         final String id = String.valueOf(++decisionCounter);
84         final String permissionResult;
85         final String message;
86         if (targetIdentifier.toLowerCase(Locale.getDefault()).contains("slow")) {
87             try {
88                 sleeper.haveALittleRest(slowResponseTimeInSeconds);
89             } catch (final InterruptedException e) {
90                 log.trace("Sleep interrupted, re-interrupting the thread");
91                 Thread.currentThread().interrupt(); // Re-interrupt the thread
92             }
93         }
94         if (targetIdentifier.toLowerCase(Locale.getDefault()).contains("cps-is-great")) {
95             permissionResult = "allow";
96             message = "All good";
97         } else {
98             permissionResult = "deny";
99             message = "Only FDNs containing 'cps-is-great' are allowed";
100         }
101         log.info("Decision: {} ({})", permissionResult, message);
102         return ResponseEntity.ok(new PermissionResponse(id, permissionResult, message));
103     }
104
105 }