5aea345777a6c7ad51a0db3b8d0a5fe60ce72dcd
[policy/xacml-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2019 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())
125                 .convertPolicy(toscaPolicy);
126             if (xacmlPolicy == null) {
127                 throw new ToscaPolicyConversionException("Failed to convert policy");
128             }
129             //
130             // Create a copy of the properties object
131             //
132             Properties newProperties = this.getProperties();
133             //
134             // Construct the filename
135             //
136             Path refPath = XacmlPolicyUtils.constructUniquePolicyFilename(xacmlPolicy, this.getDataPath());
137             //
138             // Write the policy to disk
139             // Maybe check for an error
140             //
141             XACMLPolicyWriter.writePolicyFile(refPath, xacmlPolicy);
142             if (LOGGER.isInfoEnabled()) {
143                 LOGGER.info("Xacml Policy is {}{}", XacmlPolicyUtils.LINE_SEPARATOR,
144                     new String(Files.readAllBytes(refPath), StandardCharsets.UTF_8));
145             }
146             //
147             // Add root policy to properties object
148             //
149             XacmlPolicyUtils.addRootPolicy(newProperties, refPath);
150             //
151             // Write the properties to disk
152             //
153             XacmlPolicyUtils.storeXacmlProperties(newProperties,
154                     XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
155             //
156             // Reload the engine
157             //
158             this.createEngine(newProperties);
159             //
160             // Save the properties
161             //
162             this.pdpProperties = newProperties;
163             //
164             // Save in our map
165             //
166             this.mapLoadedPolicies.put(toscaPolicy, refPath);
167         } catch (IOException | ToscaPolicyConversionException e) {
168             throw new XacmlApplicationException("loadPolicy failed", e);
169         }
170     }
171
172     @Override
173     public synchronized boolean unloadPolicy(ToscaPolicy toscaPolicy) throws XacmlApplicationException {
174         //
175         // Find it in our map
176         //
177         Path refPolicy = this.mapLoadedPolicies.get(toscaPolicy);
178         if (refPolicy == null) {
179             LOGGER.error("Failed to find ToscaPolicy {} in our map size {}", toscaPolicy.getMetadata(),
180                     this.mapLoadedPolicies.size());
181             return false;
182         }
183         //
184         // Create a copy of the properties object
185         //
186         Properties newProperties = this.getProperties();
187         //
188         // Remove it from the properties
189         //
190         XacmlPolicyUtils.removeRootPolicy(newProperties, refPolicy);
191         //
192         // We can delete the file
193         //
194         try {
195             Files.delete(refPolicy);
196         } catch (IOException e) {
197             LOGGER.error("Failed to delete policy {} from disk {}", toscaPolicy.getMetadata(),
198                     refPolicy.toAbsolutePath().toString(), e);
199         }
200         //
201         // Write the properties to disk
202         //
203         try {
204             XacmlPolicyUtils.storeXacmlProperties(newProperties,
205                     XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
206         } catch (IOException e) {
207             LOGGER.error("Failed to save the properties to disk {}", newProperties, e);
208         }
209         //
210         // Reload the engine
211         //
212         this.createEngine(newProperties);
213         //
214         // Save the properties
215         //
216         this.pdpProperties = newProperties;
217         //
218         // Save in our map
219         //
220         if (this.mapLoadedPolicies.remove(toscaPolicy) == null) {
221             LOGGER.error("Failed to remove toscaPolicy {} from internal map size {}", toscaPolicy.getMetadata(),
222                     this.mapLoadedPolicies.size());
223         }
224         //
225         // Not sure if any of the errors above warrant returning false
226         //
227         return true;
228     }
229
230     @Override
231     public Pair<DecisionResponse, Response> makeDecision(DecisionRequest request,
232             Map<String, String[]> requestQueryParams) {
233         //
234         // Convert to a XacmlRequest
235         //
236         Request xacmlRequest = this.getTranslator().convertRequest(request);
237         //
238         // Now get a decision
239         //
240         Response xacmlResponse = this.xacmlDecision(xacmlRequest);
241         //
242         // Convert to a DecisionResponse
243         //
244         return Pair.of(this.getTranslator().convertResponse(xacmlResponse), xacmlResponse);
245     }
246
247     protected abstract ToscaPolicyTranslator getTranslator(String type);
248
249     protected ToscaPolicyTranslator getTranslator() {
250         return this.getTranslator("");
251     }
252
253     protected synchronized PDPEngine getEngine() {
254         return this.pdpEngine;
255     }
256
257     protected synchronized Properties getProperties() {
258         Properties newProperties = new Properties();
259         newProperties.putAll(pdpProperties);
260         return newProperties;
261     }
262
263     protected synchronized Path getDataPath() {
264         return pathForData;
265     }
266
267     /**
268      * Creates an instance of PDP engine given the Properties object.
269      */
270     protected synchronized void createEngine(Properties properties) {
271         //
272         // Now initialize the XACML PDP Engine
273         //
274         try {
275             PDPEngineFactory factory = getPdpEngineFactory();
276             PDPEngine engine = factory.newEngine(properties);
277             if (engine != null) {
278                 this.pdpEngine = engine;
279             }
280         } catch (FactoryException e) {
281             LOGGER.error("Failed to create XACML PDP Engine {}", e);
282         }
283     }
284
285     /**
286      * Make a decision call.
287      *
288      * @param request Incoming request object
289      * @return Response object
290      */
291     protected synchronized Response xacmlDecision(Request request) {
292         //
293         // This is what we need to return
294         //
295         Response response = null;
296         //
297         // Track some timing
298         //
299         long timeStart = System.currentTimeMillis();
300         try {
301             response = this.pdpEngine.decide(request);
302         } catch (PDPException e) {
303             LOGGER.error("Xacml PDP Engine failed {}", e);
304         } finally {
305             //
306             // Track the end of timing
307             //
308             long timeEnd = System.currentTimeMillis();
309             LOGGER.info("Elapsed Time: {}ms", (timeEnd - timeStart));
310         }
311         return response;
312     }
313
314     // these may be overridden by junit tests
315
316     protected PDPEngineFactory getPdpEngineFactory() throws FactoryException {
317         return PDPEngineFactory.newInstance();
318     }
319 }