aboutsummaryrefslogtreecommitdiffstats
path: root/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java
blob: 53f1cea4b35faef446e276a2628bbe5576fc8f11 (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
/*-
 * ============LICENSE_START=======================================================
 * guard
 * ================================================================================
 * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
 * Modifications Copyright (C) 2019 Samsung Electronics Co., Ltd.
 * ================================================================================
 * 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.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.guard;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.drools.system.PolicyEngine;
import org.onap.policy.models.decisions.concepts.DecisionRequest;
import org.onap.policy.models.decisions.concepts.DecisionResponse;
import org.onap.policy.rest.RestManager;
import org.onap.policy.rest.RestManager.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class PolicyGuardXacmlHelper {
    private static final Logger logger = LoggerFactory.getLogger(PolicyGuardXacmlHelper.class);

    private String url;
    private String user;
    private String pwd;

    /**
     *  Constructor.
     */
    public PolicyGuardXacmlHelper() {
        this.url = PolicyEngine.manager.getEnvironmentProperty("guard.url");
        this.user = PolicyEngine.manager.getEnvironmentProperty("pdpx.username");
        this.pwd = PolicyEngine.manager.getEnvironmentProperty("pdpx.password");
    }

    /**
     * Call PDP.
     *
     * @param xacmlReq the XACML request
     * @return the response
     */
    public String callPdp(PolicyGuardXacmlRequestAttributes xacmlReq) {
        //
        // Create a request suitable for API
        //
        DecisionRequest decisionRequest = new DecisionRequest();
        decisionRequest.setOnapName("Policy");
        decisionRequest.setOnapComponent("Drools PDP");
        decisionRequest.setOnapInstance("usecase template");
        decisionRequest.setRequestId(UUID.randomUUID().toString());
        decisionRequest.setAction("guard");
        Map<String, String> guard = new HashMap<>();
        guard.put("actor", xacmlReq.getActorId());
        guard.put("recipe", xacmlReq.getOperationId());
        guard.put("target", xacmlReq.getTargetId());
        if (xacmlReq.getClnameId() != null) {
            guard.put("clname", xacmlReq.getClnameId());
        }
        if (xacmlReq.getVfCount() != null) {
            guard.put("vfCount", Integer.toString(xacmlReq.getVfCount()));
        }
        Map<String, Object> resources = new HashMap<>();
        resources.put("guard", guard);
        decisionRequest.setResource(resources);

        try {
            //
            // Call RESTful PDP
            //
            NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, this.url, decisionRequest.toString());
            String response = callRestfulPdp(decisionRequest);
            NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, this.url, response);

            return response;
        } catch (Exception e) {
            logger.error("Exception in sending RESTful request: ", e);
        }

        return Util.DENY;
    }

    /**
     * This makes an HTTP POST call to a running PDP RESTful servlet to get a decision.
     *
     * @param decisionRequest The Decision request
     * @return response from guard which contains "Permit" or "Deny"
     * @throws CoderException Exception when converting to/from JSON the message body
     */
    private String callRestfulPdp(DecisionRequest decisionRequest) throws CoderException {
        StandardCoder coder = new StandardCoder();

        String jsonBody = coder.encode(decisionRequest);
        RestManager restManager = new RestManager();

        Map<String, String> headers = new HashMap<>();
        headers.put("Accepts", "application/json");

        logger.info("Guard Decision Request: {}", jsonBody);

        Pair<Integer, String> httpDetails = restManager.post(url, user, pwd, headers, "application/json", jsonBody);

        if (httpDetails == null) {
            logger.error("Guard rest call returned a null pair - defaulting to DENY");
            return Util.DENY;
        }

        logger.info("Guard Decision REST Response {} {}", httpDetails.first, httpDetails.second);

        if (httpDetails.first == 200) {
            DecisionResponse decision = coder.decode(httpDetails.second, DecisionResponse.class);
            logger.info("Guard Decision {}", decision);
            return decision.getStatus();
        }

        return Util.DENY;
    }

}