5ad5068813454e1bbba8a4ee7fdae28c494ecd83
[ccsdk/oran.git] / a1-policy-management / src / main / java / org / onap / ccsdk / oran / a1policymanagementservice / controllers / authorization / AuthorizationCheck.java
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2023 Nordix Foundation. All rights reserved.
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.onap.ccsdk.oran.a1policymanagementservice.controllers.authorization;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25
26 import java.lang.invoke.MethodHandles;
27 import java.util.Map;
28
29 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
30 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
31 import org.onap.ccsdk.oran.a1policymanagementservice.clients.SecurityContext;
32 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
33 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.authorization.PolicyAuthorizationRequest.Input.AccessType;
34 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
35 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
36 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.springframework.context.annotation.DependsOn;
40 import org.springframework.http.HttpStatus;
41 import org.springframework.stereotype.Component;
42
43 import reactor.core.publisher.Mono;
44
45 @Component
46 @DependsOn("applicationContextProvider")
47 public class AuthorizationCheck {
48
49     private final ApplicationConfig applicationConfig;
50     private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
51     private final AsyncRestClient restClient;
52     private static Gson gson = new GsonBuilder().disableHtmlEscaping().create();
53
54     public AuthorizationCheck(ApplicationConfig applicationConfig, SecurityContext securityContext) {
55
56         this.applicationConfig = applicationConfig;
57         AsyncRestClientFactory restClientFactory =
58                 new AsyncRestClientFactory(applicationConfig.getWebClientConfig(), securityContext);
59         this.restClient = restClientFactory.createRestClientUseHttpProxy("");
60     }
61
62     public Mono<Policy> doAccessControl(Map<String, String> receivedHttpHeaders, Policy policy, AccessType accessType) {
63         return doAccessControl(receivedHttpHeaders, policy.getType(), accessType) //
64                 .map(x -> policy);
65     }
66
67     public Mono<PolicyType> doAccessControl(Map<String, String> receivedHttpHeaders, PolicyType type,
68             AccessType accessType) {
69         if (this.applicationConfig.getAuthProviderUrl().isEmpty()) {
70             return Mono.just(type);
71         }
72
73         String tkn = getAuthToken(receivedHttpHeaders);
74         PolicyAuthorizationRequest.Input input = PolicyAuthorizationRequest.Input.builder() //
75                 .authToken(tkn) //
76                 .policyTypeId(type.getId()) //
77                 .accessType(accessType).build();
78
79         PolicyAuthorizationRequest req = PolicyAuthorizationRequest.builder().input(input).build();
80
81         String url = this.applicationConfig.getAuthProviderUrl();
82         return this.restClient.post(url, gson.toJson(req)) //
83                 .doOnError(t -> logger.warn("Error returned from auth server: {}", t.getMessage())) //
84                 .onErrorResume(t -> Mono.just("")) //
85                 .flatMap(this::checkAuthResult) //
86                 .map(rsp -> type);
87
88     }
89
90     private String getAuthToken(Map<String, String> httpHeaders) {
91         String tkn = httpHeaders.get("authorization");
92         if (tkn == null) {
93             logger.debug("No authorization token received in {}", httpHeaders);
94             return "";
95         }
96         tkn = tkn.substring("Bearer ".length());
97         return tkn;
98     }
99
100     private Mono<String> checkAuthResult(String response) {
101         logger.debug("Auth result: {}", response);
102         try {
103             AuthorizationResult res = gson.fromJson(response, AuthorizationResult.class);
104             return res != null && res.isResult() ? Mono.just(response)
105                     : Mono.error(new ServiceException("Not authorized", HttpStatus.UNAUTHORIZED));
106         } catch (Exception e) {
107             return Mono.error(e);
108         }
109     }
110
111 }