aboutsummaryrefslogtreecommitdiffstats
path: root/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslatorTest.java
blob: cf8c0158e7e1e86871b9ade3e1f635cd4057d5ea (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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/*-
 * ============LICENSE_START=======================================================
 * ONAP
 * ================================================================================
 * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
 * Modifications Copyright (C) 2020 Nordix Foundation.
 * ================================================================================
 * 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.xacml.pdp.application.guard;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

import com.att.research.xacml.api.Decision;
import com.att.research.xacml.api.Request;
import com.att.research.xacml.std.StdMutableResponse;
import com.att.research.xacml.std.StdMutableResult;
import com.att.research.xacml.std.StdStatus;
import com.att.research.xacml.std.StdStatusCode;
import com.att.research.xacml.util.XACMLPolicyWriter;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
import org.junit.Test;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.coder.StandardYamlCoder;
import org.onap.policy.common.utils.resources.ResourceUtils;
import org.onap.policy.common.utils.resources.TextFileUtils;
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.ToscaServiceTemplate;
import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GuardTranslatorTest {
    private static final Logger LOGGER = LoggerFactory.getLogger(GuardTranslatorTest.class);
    private static final StandardYamlCoder yamlCoder = new StandardYamlCoder();
    private static StandardCoder gson = new StandardCoder();

    private GuardTranslator translator = new GuardTranslator();

    @Test
    public void testRequest() throws Exception {
        DecisionRequest decisionRequest = gson.decode(
                TextFileUtils.getTextFileAsString(
                        "src/test/resources/requests/guard.vfCount.json"),
                        DecisionRequest.class);
        Request xacmlRequest = translator.convertRequest(decisionRequest);

        assertThat(xacmlRequest).isNotNull();
    }

    @Test
    public void testResponse() {
        StdStatus status = new StdStatus(StdStatusCode.STATUS_CODE_OK);
        StdMutableResult result = new StdMutableResult(Decision.PERMIT, status);
        StdMutableResponse response = new StdMutableResponse(result);

        DecisionResponse decisionResponse = translator.convertResponse(response);
        assertThat(decisionResponse).isNotNull();
        assertThat(decisionResponse.getStatus()).isEqualTo(Decision.PERMIT.toString());

        result = new StdMutableResult(Decision.DENY, status);
        response = new StdMutableResponse(result);
        decisionResponse = translator.convertResponse(response);
        assertThat(decisionResponse).isNotNull();
        assertThat(decisionResponse.getStatus()).isEqualTo(Decision.DENY.toString());

        result = new StdMutableResult(Decision.INDETERMINATE, status);
        response = new StdMutableResponse(result);
        decisionResponse = translator.convertResponse(response);
        assertThat(decisionResponse).isNotNull();
        assertThat(decisionResponse.getStatus()).isEqualTo(Decision.PERMIT.toString());
    }


    @Test
    public void testBadPolicies() throws Exception {
        String policyYaml = ResourceUtils.getResourceAsString("src/test/resources/test-bad-policies.yaml");
        //
        // Serialize it into a class
        //
        ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
        //
        // Make sure all the fields are setup properly
        //
        JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
        jtst.fromAuthorative(serviceTemplate);
        final ToscaServiceTemplate completedJtst = jtst.toAuthorative();
        //
        // Expected message for given policy name
        //
        final Map<String, String> name2message = new HashMap<>();
        name2message.put("frequency-missing-properties", "Missing property limit");
        name2message.put("frequency-timewindow", "timeWindow is not an integer");
        name2message.put("frequency-badtimerange_start", "Invalid timeRange");
        name2message.put("frequency-badtimerange_end", "Invalid timeRange");
        name2message.put("frequency-badtimerange_value", "timestamp 99:99:99 could not be parsed");
        name2message.put("minmax-notarget", "Missing target field in minmax policy");
        name2message.put("minmax-nominmax", "Missing min or max field in minmax policy");
        name2message.put("blacklist-noblacklist", "Missing blacklist");
        name2message.put("filter-noalgorithm", "Missing algorithm");
        name2message.put("filter-badalgorithm",
                            "Unexpected value for algorithm, should be whitelist-overrides or blacklist-overrides");
        name2message.put("filter-nofilter", "Missing filters");
        name2message.put("filter-nocollection", "Filters is not a collection");
        name2message.put("filter-noarray", "Filters is not a collection");
        name2message.put("filter-missingfield", "Missing \'field\' from filter");
        name2message.put("filter-badfield", "Unexpected value for field in filter");
        name2message.put("filter-missingfilter", "Missing \'filter\' from filter");
        name2message.put("filter-missingfunction", "Missing \'function\' from filter");
        name2message.put("filter-badfunction", "Unexpected value for function in filter");
        name2message.put("filter-missingblacklist", "Missing \'blacklist\' from filter");
        name2message.put("filter-badblacklist", "Unexpected value for blacklist in filter");
        //
        // Get the policies
        //
        for (Map<String, ToscaPolicy> policies : completedJtst.getToscaTopologyTemplate().getPolicies()) {
            for (ToscaPolicy policy : policies.values()) {
                LOGGER.info("Testing policy " + policy.getName());
                String expectedMsg = name2message.get(policy.getName());
                assertThat(expectedMsg).as(policy.getName()).isNotNull();

                assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
                    translator.convertPolicy(policy)
                ).withMessageContaining(expectedMsg);
            }
        }
    }

    @Test
    public void testPolicyConversion() throws Exception {
        String policyYaml = ResourceUtils.getResourceAsString("src/test/resources/test-policies.yaml");
        //
        // Serialize it into a class
        //
        ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
        //
        // Make sure all the fields are setup properly
        //
        JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
        jtst.fromAuthorative(serviceTemplate);
        ToscaServiceTemplate completedJtst = jtst.toAuthorative();
        //
        // Get the policies
        //
        for (Map<String, ToscaPolicy> policies : completedJtst.getToscaTopologyTemplate().getPolicies()) {
            for (ToscaPolicy policy : policies.values()) {
                //
                // Convert the policy
                //
                if ("onap.policies.controlloop.guard.common.Unknown".equals(policy.getType())) {
                    assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
                        translator.convertPolicy(policy));
                    continue;
                }
                PolicyType xacmlPolicy = (PolicyType) translator.convertPolicy(policy);
                assertThat(xacmlPolicy).isNotNull();
                //
                // Let's dump it out
                //
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                XACMLPolicyWriter.writePolicyFile(os, xacmlPolicy);
                LOGGER.info(os.toString());
                //
                // Validate the policy
                //
                assertThat(xacmlPolicy.getPolicyId()).isEqualTo(policy.getName());
                assertThat(xacmlPolicy.getVersion()).isEqualTo(policy.getVersion());
                assertThat(xacmlPolicy.getRuleCombiningAlgId()).isNotNull();
                validateCommon(policy, xacmlPolicy);
                //
                // Validate each policy type
                //
                if (GuardTranslator.POLICYTYPE_FREQUENCY.equals(policy.getType())) {
                    validateFrequency(policy, xacmlPolicy);
                } else if (GuardTranslator.POLICYTYPE_MINMAX.equals(policy.getType())) {
                    validateMinMax(policy, xacmlPolicy);
                } else if (GuardTranslator.POLICYTYPE_BLACKLIST.equals(policy.getType())) {
                    validateBlacklist(policy, xacmlPolicy);
                } else if (GuardTranslator.POLICYTYPE_FILTER.equals(policy.getType())) {
                    validateFilter(policy, xacmlPolicy);
                }
            }
        }

        ToscaPolicy testPol = completedJtst.getToscaTopologyTemplate().getPolicies().get(0).values().iterator().next();

        testPol.setProperties(new LinkedHashMap<>());
        assertThatExceptionOfType(ToscaPolicyConversionException.class)
                .isThrownBy(() -> translator.convertPolicy(testPol));

        testPol.setProperties(null);
        assertThatExceptionOfType(ToscaPolicyConversionException.class)
                .isThrownBy(() -> translator.convertPolicy(testPol));
    }

    private void validateCommon(ToscaPolicy policy, PolicyType xacmlPolicy) {
        boolean foundActor = false;
        boolean foundOperation = false;
        boolean foundTarget = false;
        boolean foundControlLoop = false;
        //boolean foundTimeRange = false;

        assertThat(xacmlPolicy.getTarget()).isNotNull();
        assertThat(xacmlPolicy.getTarget().getAnyOf()).isNotEmpty();
        for (AnyOfType anyOf : xacmlPolicy.getTarget().getAnyOf()) {
            assertThat(anyOf.getAllOf()).isNotEmpty();
            for (AllOfType allOf : anyOf.getAllOf()) {
                assertThat(allOf.getMatch()).isNotEmpty();
                for (MatchType match : allOf.getMatch()) {
                    //
                    // These fields are required
                    //
                    if (ToscaDictionary.ID_RESOURCE_GUARD_ACTOR.toString().equals(
                            match.getAttributeDesignator().getAttributeId())) {
                        assertThat(match.getAttributeValue().getContent()).isNotNull();
                        foundActor = true;
                    } else if (ToscaDictionary.ID_RESOURCE_GUARD_RECIPE.toString().equals(
                            match.getAttributeDesignator().getAttributeId())) {
                        assertThat(match.getAttributeValue().getContent()).isNotNull();
                        foundOperation = true;
                    } else {
                        //
                        // These fields are optional
                        //
                        if (ToscaDictionary.ID_RESOURCE_GUARD_TARGETID.toString().equals(
                                match.getAttributeDesignator().getAttributeId())) {
                            assertThat(policy.getProperties()).containsKey("target");
                            foundTarget = true;
                        }
                        if (ToscaDictionary.ID_RESOURCE_GUARD_CLNAME.toString().equals(
                                match.getAttributeDesignator().getAttributeId())) {
                            assertThat(policy.getProperties()).containsKey(GuardTranslator.FIELD_CONTROLLOOP);
                            foundControlLoop = true;
                        }
                        /*
                        if (XACML3.ID_ENVIRONMENT_CURRENT_TIME.toString().equals(
                                match.getAttributeDesignator().getAttributeId())) {
                            assertThat(policy.getProperties()).containsKey(GuardTranslator.FIELD_TIMERANGE);
                            foundTimeRange = true;
                        }
                        */
                    }
                }
            }
        }
        assertThat(foundActor && foundOperation).isTrue();
        if (policy.getProperties().containsKey("target")) {
            assertThat(foundTarget).isTrue();
        }
        if (policy.getProperties().containsKey(GuardTranslator.FIELD_CONTROLLOOP)) {
            assertThat(foundControlLoop).isTrue();
        }
        if (policy.getProperties().containsKey(GuardTranslator.FIELD_TIMERANGE)) {
            assertThat(xacmlPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition())
                .hasAtLeastOneElementOfType(VariableDefinitionType.class);
        }
    }

    private void validateFrequency(ToscaPolicy policy, PolicyType xacmlPolicy) {
        for (Object rule : xacmlPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) {
            if (! (rule instanceof RuleType)) {
                continue;
            }
            assertThat(((RuleType) rule).getCondition()).isNotNull();
            assertThat(((RuleType) rule).getCondition().getExpression()).isNotNull();
        }
    }

    private void validateMinMax(ToscaPolicy policy, PolicyType xacmlPolicy) {
        boolean foundTarget = false;
        boolean foundMinOrMax = false;
        for (Object rule : xacmlPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) {
            if (! (rule instanceof RuleType)) {
                continue;
            }
            for (AnyOfType anyOf : ((RuleType) rule).getTarget().getAnyOf()) {
                assertThat(anyOf.getAllOf()).isNotEmpty();
                for (AllOfType allOf : anyOf.getAllOf()) {
                    assertThat(allOf.getMatch()).isNotEmpty();
                    for (MatchType match : allOf.getMatch()) {
                        if (ToscaDictionary.ID_RESOURCE_GUARD_TARGETID.toString().equals(
                                match.getAttributeDesignator().getAttributeId())) {
                            assertThat(policy.getProperties()).containsKey(GuardTranslator.FIELD_TARGET);
                            foundTarget = true;
                        } else if (ToscaDictionary.ID_RESOURCE_GUARD_VFCOUNT.toString().equals(
                                match.getAttributeDesignator().getAttributeId())) {
                            assertThat(policy.getProperties().keySet()).containsAnyOf(GuardTranslator.FIELD_MIN,
                                    GuardTranslator.FIELD_MAX);
                            foundMinOrMax = true;
                        }
                    }
                }
            }
        }
        assertThat(foundTarget && foundMinOrMax).isTrue();
    }

    private void validateBlacklist(ToscaPolicy policy, PolicyType xacmlPolicy) {
        boolean foundBlacklist = false;
        for (Object rule : xacmlPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) {
            if (! (rule instanceof RuleType)) {
                continue;
            }
            assertThat(((RuleType) rule).getTarget()).isNotNull();
            assertThat(((RuleType) rule).getTarget().getAnyOf()).hasSize(1);
            for (AnyOfType anyOf : ((RuleType) rule).getTarget().getAnyOf()) {
                assertThat(anyOf.getAllOf()).isNotEmpty();
                for (AllOfType allOf : anyOf.getAllOf()) {
                    assertThat(allOf.getMatch()).isNotEmpty();
                    assertThat(allOf.getMatch()).hasSize(1);
                    for (MatchType match : allOf.getMatch()) {
                        assertThat(match.getAttributeDesignator().getAttributeId())
                                .isEqualTo(ToscaDictionary.ID_RESOURCE_GUARD_TARGETID.toString());
                        assertThat(match.getAttributeValue().getContent()).containsAnyOf("vnf1", "vnf2");
                        //
                        // This just checks that policy did have a blacklist in it.
                        //
                        assertThat(policy.getProperties()).containsKey(GuardTranslator.FIELD_BLACKLIST);
                        foundBlacklist = true;
                    }
                }
            }
        }
        assertThat(foundBlacklist).isTrue();
    }

    private void validateFilter(ToscaPolicy policy, PolicyType xacmlPolicy) {
        assertThat(xacmlPolicy.getRuleCombiningAlgId()).endsWith("-overrides");
        for (Object rule : xacmlPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) {
            if (! (rule instanceof RuleType)) {
                continue;
            }
            assertThat(((RuleType) rule).getTarget()).isNotNull();
            assertThat(((RuleType) rule).getTarget().getAnyOf()).hasSize(1);
            for (AnyOfType anyOf : ((RuleType) rule).getTarget().getAnyOf()) {
                assertThat(anyOf.getAllOf()).isNotEmpty();
                for (AllOfType allOf : anyOf.getAllOf()) {
                    assertThat(allOf.getMatch()).isNotEmpty();
                    assertThat(allOf.getMatch()).hasSize(1);
                    for (MatchType match : allOf.getMatch()) {
                        assertThat(match.getAttributeDesignator().getAttributeId())
                            .startsWith(GuardPolicyRequest.PREFIX_RESOURCE_ATTRIBUTE_ID);
                    }
                }
            }
        }
    }
}