aboutsummaryrefslogtreecommitdiffstats
path: root/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProvider.java
blob: 1dd30ec4f0ebcd1920fea563bd7a19edf336b190 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/*-
 * ============LICENSE_START=======================================================
 * ONAP
 * ================================================================================
 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.pdp.xacml.application.common.std;

import com.att.research.xacml.api.Request;
import com.att.research.xacml.api.Response;
import com.att.research.xacml.api.pdp.PDPEngine;
import com.att.research.xacml.api.pdp.PDPEngineFactory;
import com.att.research.xacml.api.pdp.PDPException;
import com.att.research.xacml.util.FactoryException;
import com.att.research.xacml.util.XACMLPolicyWriter;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;

import org.apache.commons.lang3.tuple.Pair;
import org.onap.policy.models.decisions.concepts.DecisionRequest;
import org.onap.policy.models.decisions.concepts.DecisionResponse;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class StdXacmlApplicationServiceProvider implements XacmlApplicationServiceProvider {

    private static final Logger LOGGER = LoggerFactory.getLogger(StdXacmlApplicationServiceProvider.class);
    private Path pathForData = null;
    private Properties pdpProperties = null;
    private PDPEngine pdpEngine = null;
    private Map<ToscaPolicy, Path> mapLoadedPolicies = new HashMap<>();

    public StdXacmlApplicationServiceProvider() {
        super();
    }

    @Override
    public String applicationName() {
        return "Please Override";
    }

    @Override
    public List<String> actionDecisionsSupported() {
        return Collections.emptyList();
    }

    @Override
    public void initialize(Path pathForData) throws XacmlApplicationException {
        //
        // Save our path
        //
        this.pathForData = pathForData;
        LOGGER.info("New Path is {}", this.pathForData.toAbsolutePath());
        //
        // Ensure properties exist
        //
        Path propertiesPath = XacmlPolicyUtils.getPropertiesPath(pathForData);
        if (! propertiesPath.toFile().exists()) {
            LOGGER.info("Copying src/main/resources/xacml.properties to path");
            //
            // Properties do not exist, by default we will copy ours over
            // from src/main/resources
            //
            try {
                Files.copy(Paths.get("src/main/resources/xacml.properties"), propertiesPath);
            } catch (IOException e) {
                throw new XacmlApplicationException("Failed to copy xacml.propertis", e);
            }
        }
        //
        // Look for and load the properties object
        //
        try {
            pdpProperties = XacmlPolicyUtils.loadXacmlProperties(XacmlPolicyUtils.getPropertiesPath(pathForData));
            LOGGER.info("{}", pdpProperties);
        } catch (IOException e) {
            throw new XacmlApplicationException("Failed to load xacml.propertis", e);
        }
        //
        // Create an engine
        //
        createEngine(pdpProperties);
    }

    @Override
    public List<ToscaPolicyTypeIdentifier> supportedPolicyTypes() {
        throw new UnsupportedOperationException("Please override and implement supportedPolicyTypes");
    }

    @Override
    public boolean canSupportPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
        throw new UnsupportedOperationException("Please override and implement canSupportPolicyType");
    }

    @Override
    public synchronized boolean loadPolicy(ToscaPolicy toscaPolicy) {
        try {
            //
            // Convert the policies first
            //
            PolicyType xacmlPolicy = this.getTranslator(toscaPolicy.getType())
                .convertPolicy(toscaPolicy);
            if (xacmlPolicy == null) {
                throw new ToscaPolicyConversionException("Failed to convert policy");
            }
            //
            // Create a copy of the properties object
            //
            Properties newProperties = this.getProperties();
            //
            // Construct the filename
            //
            Path refPath = XacmlPolicyUtils.constructUniquePolicyFilename(xacmlPolicy, this.getDataPath());
            //
            // Write the policy to disk
            // Maybe check for an error
            //
            XACMLPolicyWriter.writePolicyFile(refPath, xacmlPolicy);
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Xacml Policy is {}{}", System.lineSeparator(), new String(Files.readAllBytes(refPath)));
            }
            //
            // Add root policy to properties object
            //
            XacmlPolicyUtils.addRootPolicy(newProperties, refPath);
            //
            // Write the properties to disk
            //
            XacmlPolicyUtils.storeXacmlProperties(newProperties,
                    XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
            //
            // Reload the engine
            //
            this.createEngine(newProperties);
            //
            // Save the properties
            //
            this.pdpProperties = newProperties;
            //
            // Save in our map
            //
            this.mapLoadedPolicies.put(toscaPolicy, refPath);
        } catch (IOException | ToscaPolicyConversionException e) {
            LOGGER.error("Failed to loadPolicies {}", e);
            return false;
        }
        return true;
    }

    @Override
    public synchronized boolean unloadPolicy(ToscaPolicy toscaPolicy) throws XacmlApplicationException {
        //
        // Find it in our map
        //
        Path refPolicy = this.mapLoadedPolicies.get(toscaPolicy);
        if (refPolicy == null) {
            LOGGER.error("Failed to find ToscaPolicy {} in our map size {}", toscaPolicy.getMetadata(),
                    this.mapLoadedPolicies.size());
            return false;
        }
        //
        // Create a copy of the properties object
        //
        Properties newProperties = this.getProperties();
        //
        // Remove it from the properties
        //
        XacmlPolicyUtils.removeRootPolicy(newProperties, refPolicy);
        //
        // We can delete the file
        //
        try {
            Files.delete(refPolicy);
        } catch (IOException e) {
            LOGGER.error("Failed to delete policy {} from disk {}", toscaPolicy.getMetadata(),
                    refPolicy.toAbsolutePath().toString(), e);
        }
        //
        // Write the properties to disk
        //
        try {
            XacmlPolicyUtils.storeXacmlProperties(newProperties,
                    XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
        } catch (IOException e) {
            LOGGER.error("Failed to save the properties to disk {}", newProperties, e);
        }
        //
        // Reload the engine
        //
        this.createEngine(newProperties);
        //
        // Save the properties
        //
        this.pdpProperties = newProperties;
        //
        // Save in our map
        //
        if (this.mapLoadedPolicies.remove(toscaPolicy) == null) {
            LOGGER.error("Failed to remove toscaPolicy {} from internal map size {}", toscaPolicy.getMetadata(),
                    this.mapLoadedPolicies.size());
        }
        //
        // Not sure if any of the errors above warrant returning false
        //
        return true;
    }

    @Override
    public Pair<DecisionResponse, Response> makeDecision(DecisionRequest request) {
        //
        // Convert to a XacmlRequest
        //
        Request xacmlRequest = this.getTranslator().convertRequest(request);
        //
        // Now get a decision
        //
        Response xacmlResponse = this.xacmlDecision(xacmlRequest);
        //
        // Convert to a DecisionResponse
        //
        return Pair.of(this.getTranslator().convertResponse(xacmlResponse), xacmlResponse);
    }

    protected abstract ToscaPolicyTranslator getTranslator(String type);

    protected ToscaPolicyTranslator getTranslator() {
        return this.getTranslator("");
    }

    protected synchronized PDPEngine getEngine() {
        return this.pdpEngine;
    }

    protected synchronized Properties getProperties() {
        Properties newProperties = new Properties();
        newProperties.putAll(pdpProperties);
        return newProperties;
    }

    protected synchronized Path getDataPath() {
        return pathForData;
    }

    /**
     * Load properties from given file.
     *
     * @throws IOException If unable to read file
     */
    protected synchronized Properties loadXacmlProperties() throws IOException {
        LOGGER.info("Loading xacml properties {}", pathForData);
        try (InputStream is = Files.newInputStream(pathForData)) {
            Properties properties = new Properties();
            properties.load(is);
            return properties;
        }
    }

    /**
     * Stores the XACML Properties to the given file location.
     *
     * @throws IOException If unable to store the file.
     */
    protected synchronized void storeXacmlProperties() throws IOException {
        try (OutputStream os = Files.newOutputStream(pathForData)) {
            String strComments = "#";
            pdpProperties.store(os, strComments);
        }
    }

    /**
     * Appends 'xacml.properties' to a root Path object
     *
     * @return Path to rootPath/xacml.properties file
     */
    protected synchronized Path getPropertiesPath() {
        return Paths.get(pathForData.toAbsolutePath().toString(), "xacml.properties");
    }

    /**
     * Creates an instance of PDP engine given the Properties object.
     */
    protected synchronized void createEngine(Properties properties) {
        //
        // Now initialize the XACML PDP Engine
        //
        try {
            PDPEngineFactory factory = PDPEngineFactory.newInstance();
            PDPEngine engine = factory.newEngine(properties);
            if (engine != null) {
                this.pdpEngine = engine;
            }
        } catch (FactoryException e) {
            LOGGER.error("Failed to create XACML PDP Engine {}", e);
        }
    }

    /**
     * Make a decision call.
     *
     * @param request Incoming request object
     * @return Response object
     */
    protected synchronized Response xacmlDecision(Request request) {
        //
        // This is what we need to return
        //
        Response response = null;
        //
        // Track some timing
        //
        long timeStart = System.currentTimeMillis();
        try {
            response = this.pdpEngine.decide(request);
        } catch (PDPException e) {
            LOGGER.error("Xacml PDP Engine failed {}", e);
        } finally {
            //
            // Track the end of timing
            //
            long timeEnd = System.currentTimeMillis();
            LOGGER.info("Elapsed Time: {}ms", (timeEnd - timeStart));
        }
        return response;
    }

}