Merge "Added support for application/xacml+json in native app"
[policy/xacml-pdp.git] / applications / common / src / main / java / org / onap / policy / pdp / xacml / application / common / std / StdXacmlApplicationServiceProvider.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2019-2020 AT&T Intellectual Property. 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  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.pdp.xacml.application.common.std;
24
25 import com.att.research.xacml.api.Request;
26 import com.att.research.xacml.api.Response;
27 import com.att.research.xacml.api.pdp.PDPEngine;
28 import com.att.research.xacml.api.pdp.PDPEngineFactory;
29 import com.att.research.xacml.api.pdp.PDPException;
30 import com.att.research.xacml.util.FactoryException;
31 import com.att.research.xacml.util.XACMLPolicyWriter;
32 import java.io.IOException;
33 import java.nio.charset.StandardCharsets;
34 import java.nio.file.Files;
35 import java.nio.file.Path;
36 import java.util.Collections;
37 import java.util.HashMap;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.Properties;
41 import lombok.Getter;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
43 import org.apache.commons.lang3.tuple.Pair;
44 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
45 import org.onap.policy.models.decisions.concepts.DecisionRequest;
46 import org.onap.policy.models.decisions.concepts.DecisionResponse;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
49 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
50 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
51 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
52 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
53 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 public abstract class StdXacmlApplicationServiceProvider implements XacmlApplicationServiceProvider {
58
59     private static final Logger LOGGER = LoggerFactory.getLogger(StdXacmlApplicationServiceProvider.class);
60     private Path pathForData = null;
61     @Getter
62     private RestServerParameters policyApiParameters;
63     private Properties pdpProperties = null;
64     private PDPEngine pdpEngine = null;
65     private Map<ToscaPolicy, Path> mapLoadedPolicies = new HashMap<>();
66
67     public StdXacmlApplicationServiceProvider() {
68         super();
69     }
70
71     @Override
72     public String applicationName() {
73         return "Please Override";
74     }
75
76     @Override
77     public List<String> actionDecisionsSupported() {
78         return Collections.emptyList();
79     }
80
81     @Override
82     public void initialize(Path pathForData, RestServerParameters policyApiParameters)
83             throws XacmlApplicationException {
84         //
85         // Save our path
86         //
87         this.pathForData = pathForData;
88         LOGGER.info("New Path is {}", this.pathForData.toAbsolutePath());
89         //
90         // Save our params
91         //
92         this.policyApiParameters = policyApiParameters;
93         //
94         // Look for and load the properties object
95         //
96         try {
97             pdpProperties = XacmlPolicyUtils.loadXacmlProperties(XacmlPolicyUtils.getPropertiesPath(pathForData));
98             LOGGER.info("{}", pdpProperties);
99         } catch (IOException e) {
100             throw new XacmlApplicationException("Failed to load " + XacmlPolicyUtils.XACML_PROPERTY_FILE, e);
101         }
102         //
103         // Create an engine
104         //
105         createEngine(pdpProperties);
106     }
107
108     @Override
109     public List<ToscaPolicyTypeIdentifier> supportedPolicyTypes() {
110         throw new UnsupportedOperationException("Please override and implement supportedPolicyTypes");
111     }
112
113     @Override
114     public boolean canSupportPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
115         throw new UnsupportedOperationException("Please override and implement canSupportPolicyType");
116     }
117
118     @Override
119     public synchronized void loadPolicy(ToscaPolicy toscaPolicy) throws XacmlApplicationException {
120         try {
121             //
122             // Convert the policies first
123             //
124             PolicyType xacmlPolicy = this.getTranslator(toscaPolicy.getType()).convertPolicy(toscaPolicy);
125             if (xacmlPolicy == null) {
126                 throw new ToscaPolicyConversionException("Failed to convert policy");
127             }
128             //
129             // Create a copy of the properties object
130             //
131             Properties newProperties = this.getProperties();
132             //
133             // Construct the filename
134             //
135             Path refPath = XacmlPolicyUtils.constructUniquePolicyFilename(xacmlPolicy, this.getDataPath());
136             //
137             // Write the policy to disk
138             // Maybe check for an error
139             //
140             XACMLPolicyWriter.writePolicyFile(refPath, xacmlPolicy);
141             if (LOGGER.isInfoEnabled()) {
142                 LOGGER.info("Xacml Policy is {}{}", XacmlPolicyUtils.LINE_SEPARATOR,
143                     new String(Files.readAllBytes(refPath), StandardCharsets.UTF_8));
144             }
145             //
146             // Add root policy to properties object
147             //
148             XacmlPolicyUtils.addRootPolicy(newProperties, refPath);
149             //
150             // Write the properties to disk
151             //
152             XacmlPolicyUtils.storeXacmlProperties(newProperties,
153                     XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
154             //
155             // Reload the engine
156             //
157             this.createEngine(newProperties);
158             //
159             // Save the properties
160             //
161             this.pdpProperties = newProperties;
162             //
163             // Save in our map
164             //
165             this.mapLoadedPolicies.put(toscaPolicy, refPath);
166         } catch (IOException | ToscaPolicyConversionException e) {
167             throw new XacmlApplicationException("loadPolicy failed", e);
168         }
169     }
170
171     @Override
172     public synchronized boolean unloadPolicy(ToscaPolicy toscaPolicy) throws XacmlApplicationException {
173         //
174         // Find it in our map
175         //
176         Path refPolicy = this.mapLoadedPolicies.get(toscaPolicy);
177         if (refPolicy == null) {
178             LOGGER.error("Failed to find ToscaPolicy {} in our map size {}", toscaPolicy.getMetadata(),
179                     this.mapLoadedPolicies.size());
180             return false;
181         }
182         //
183         // Create a copy of the properties object
184         //
185         Properties newProperties = this.getProperties();
186         //
187         // Remove it from the properties
188         //
189         XacmlPolicyUtils.removeRootPolicy(newProperties, refPolicy);
190         //
191         // We can delete the file
192         //
193         try {
194             Files.delete(refPolicy);
195         } catch (IOException e) {
196             LOGGER.error("Failed to delete policy {} from disk {}", toscaPolicy.getMetadata(),
197                     refPolicy.toAbsolutePath(), e);
198         }
199         //
200         // Write the properties to disk
201         //
202         try {
203             XacmlPolicyUtils.storeXacmlProperties(newProperties,
204                     XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
205         } catch (IOException e) {
206             LOGGER.error("Failed to save the properties to disk {}", newProperties, e);
207         }
208         //
209         // Reload the engine
210         //
211         this.createEngine(newProperties);
212         //
213         // Save the properties
214         //
215         this.pdpProperties = newProperties;
216         //
217         // Save in our map
218         //
219         if (this.mapLoadedPolicies.remove(toscaPolicy) == null) {
220             LOGGER.error("Failed to remove toscaPolicy {} from internal map size {}", toscaPolicy.getMetadata(),
221                     this.mapLoadedPolicies.size());
222         }
223         //
224         // Not sure if any of the errors above warrant returning false
225         //
226         return true;
227     }
228
229     @Override
230     public Pair<DecisionResponse, Response> makeDecision(DecisionRequest request,
231             Map<String, String[]> requestQueryParams) {
232         //
233         // Convert to a XacmlRequest
234         //
235         Request xacmlRequest = this.getTranslator().convertRequest(request);
236         //
237         // Now get a decision
238         //
239         Response xacmlResponse = this.xacmlDecision(xacmlRequest);
240         //
241         // Convert to a DecisionResponse
242         //
243         return Pair.of(this.getTranslator().convertResponse(xacmlResponse), xacmlResponse);
244     }
245
246     protected abstract ToscaPolicyTranslator getTranslator(String type);
247
248     protected ToscaPolicyTranslator getTranslator() {
249         return this.getTranslator("");
250     }
251
252     protected synchronized PDPEngine getEngine() {
253         return this.pdpEngine;
254     }
255
256     protected synchronized Properties getProperties() {
257         Properties newProperties = new Properties();
258         newProperties.putAll(pdpProperties);
259         return newProperties;
260     }
261
262     protected synchronized Path getDataPath() {
263         return pathForData;
264     }
265
266     /**
267      * Creates an instance of PDP engine given the Properties object.
268      */
269     protected synchronized void createEngine(Properties properties) {
270         //
271         // Now initialize the XACML PDP Engine
272         //
273         try {
274             PDPEngineFactory factory = getPdpEngineFactory();
275             PDPEngine engine = factory.newEngine(properties);
276             if (engine != null) {
277                 this.pdpEngine = engine;
278             }
279         } catch (FactoryException e) {
280             LOGGER.error("Failed to create XACML PDP Engine", e);
281         }
282     }
283
284     /**
285      * Make a decision call.
286      *
287      * @param request Incoming request object
288      * @return Response object
289      */
290     protected synchronized Response xacmlDecision(Request request) {
291         //
292         // This is what we need to return
293         //
294         Response response = null;
295         //
296         // Track some timing
297         //
298         long timeStart = System.currentTimeMillis();
299         try {
300             response = this.pdpEngine.decide(request);
301         } catch (PDPException e) {
302             LOGGER.error("Xacml PDP Engine decide failed", e);
303         } finally {
304             //
305             // Track the end of timing
306             //
307             long timeEnd = System.currentTimeMillis();
308             LOGGER.info("Elapsed Time: {}ms", (timeEnd - timeStart));
309         }
310         return response;
311     }
312
313     // these may be overridden by junit tests
314
315     protected PDPEngineFactory getPdpEngineFactory() throws FactoryException {
316         return PDPEngineFactory.newInstance();
317     }
318 }