aboutsummaryrefslogtreecommitdiffstats
path: root/moon_manager/moon_manager/api/pdp.py
blob: 6f0b5214b456f4cc863a57596a0b27720694aa29 (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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# Software Name: MOON

# Version: 5.4

# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors
# SPDX-License-Identifier: Apache-2.0

# This software is distributed under the 'Apache License 2.0',
# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt'
# or see the "LICENSE" file for more details.

"""
PDP are Policy Decision Points.

"""

import hug
import json
import logging
import requests
from moon_manager.api import ERROR_CODE
from moon_manager import db_driver
from moon_utilities.auth_functions import api_key_authentication, connect_from_env
from moon_manager import orchestration_driver
from moon_utilities import exceptions
from moon_utilities.security_functions import validate_input
from moon_utilities.invalided_functions import invalidate_pdp_in_slaves
from moon_manager.api import slave as slave_class
from moon_manager.api import configuration

LOGGER = logging.getLogger("moon.manager.api." + __name__)


class PDP(object):
    """
    Endpoint for pdp requests
    """

    @staticmethod
    @hug.local()
    @hug.get("/pdp/", requires=api_key_authentication)
    @hug.get("/pdp/{uuid}", requires=api_key_authentication)
    def get(uuid: hug.types.uuid = None, authed_user: hug.directives.user = None):
        """Retrieve all pdp

        :param uuid: uuid of the pdp
        :param authed_user: the name of the authenticated user
        :return: {
            "pdp_id1": {
                "name": "...",
                "security_pipeline": [...],
                "vim_project_id": "vim_project_id1",
                "description": "... (optional)",
            }
        }
        :internal_api: get_pdp
        """
        if uuid:
            uuid = str(uuid).replace("-", "")
        data = db_driver.PDPManager.get_pdp(moon_user_id=authed_user, pdp_id=uuid)

        return {"pdps": data}

    @staticmethod
    @hug.local()
    @hug.post("/pdp/", requires=api_key_authentication)
    def post(body: validate_input("name"), response, authed_user: hug.directives.user = None):
        """Create pdp.

        :param body: preformed body from Hug
        :param response: preformed response from Hug
        :param authed_user: the name of the authenticated user
        :request body: {
            "name": "name of the PDP (mandatory)",
            "security_pipeline": ["may be empty"],
            "vim_project_id": "vim_project_id1 (may be empty)",
            "description": "description of the PDP (optional)",
        }
        :return: {
            "pdp_id1": {
                "name": "...",
                "security_pipeline": [...],
                "vim_project_id": "vim_project_id1",
                "description": "... (optional)",
            }
        }
        :internal_api: add_pdp
        """
        if not body.get("security_pipeline"):
            body["security_pipeline"] = []
        if not body.get("vim_project_id"):
            body["vim_project_id"] = None
        data = db_driver.PDPManager.add_pdp(
            moon_user_id="admin", pdp_id=None, value=body)
        uuid = list(data.keys())[0]
        if body["vim_project_id"] and body["security_pipeline"]:
            orchestration_driver.PipelineManager.add_pipeline(
                moon_user_id=authed_user, pipeline_id=uuid, data=data[uuid])
        return {"pdps": db_driver.PDPManager.get_pdp(moon_user_id=authed_user, pdp_id=uuid)}

    @staticmethod
    @hug.local()
    @hug.delete("/pdp/{uuid}", requires=api_key_authentication)
    def delete(uuid: hug.types.uuid, response=None, authed_user: hug.directives.user = None):
        """Delete a pdp

        :param uuid: uuid of the pdp to delete
        :param response: preformed response from Hug
        :param authed_user: the name of the authenticated user
        :return: {
            "result": "True or False",
            "message": "optional message (optional)"
        }
        :internal_api: delete_pdp
        """
        uuid = str(uuid).replace("-", "")
        data = db_driver.PDPManager.delete_pdp(moon_user_id=authed_user, pdp_id=uuid)

        LOGGER.info(data)

        orchestration_driver.PipelineManager.delete_pipeline(moon_user_id=authed_user, pipeline_id=uuid)
        slaves = slave_class.Slaves.get().get("slaves")
        invalidate_pdp_in_slaves(slaves=slaves, pdp_id=uuid)
        return {"result": True}

    @staticmethod
    @hug.local()
    @hug.patch("/pdp/{uuid}", requires=api_key_authentication)
    def patch(uuid: hug.types.uuid, body: validate_input("name"), response,
              authed_user: hug.directives.user = None):
        """Update a pdp

        :param uuid: uuid of the pdp to delete
        :param body: preformed body from Hug
        :param response: preformed response from Hug
        :param authed_user: the name of the authenticated user
        :return: {
            "pdp_id1": {
                "name": "name of the PDP",
                "security_pipeline": ["may be empty"],
                "vim_project_id": "vim_project_id1 (may be empty)",
                "description": "description of the PDP (optional)",
            }
        }
        :internal_api: update_pdp
        """

        uuid = str(uuid).replace("-", "")
        prev_data = db_driver.PDPManager.get_pdp(moon_user_id=authed_user, pdp_id=uuid)
        if not prev_data:
            response.status = ERROR_CODE[400]
            return {"message": "The PDP is unknown."}

        data = db_driver.PDPManager.update_pdp(moon_user_id=authed_user, pdp_id=uuid, value=body).get(uuid)

        orchestration_driver.PipelineManager.update_pipeline(moon_user_id=authed_user, pipeline_id=uuid, data=data)
        slaves = slave_class.Slaves.get().get("slaves")
        invalidate_pdp_in_slaves(slaves=slaves, pdp_id=uuid, is_delete=False, data=data)

        return {"pdps": db_driver.PDPManager.get_pdp(moon_user_id=authed_user, pdp_id=uuid)}


PDPAPI = hug.API(name='pdps', doc=PDP.__doc__)


@hug.object(name='pdps', version='1.0.0', api=PDPAPI)
class PDPCLI(object):
    """An example of command like calls via an Object"""

    @staticmethod
    @hug.object.cli
    def list(name_or_id="", human: bool = False):
        db_conf = configuration.get_configuration(key='management')
        manager_api_key = connect_from_env()
        _pdps = requests.get("{}/pdp".format(db_conf.get("url")),
                             headers={"x-api-key": manager_api_key}
                             )
        if _pdps.status_code == 200:
            if name_or_id:
                _pdp = None
                if name_or_id in _pdps.json().get("pdps"):
                    _pdp = _pdps.json().get("pdps").get(name_or_id)
                else:
                    for _pdp_key in _pdps.json().get("pdps"):
                        if _pdps.json().get("pdps").get(_pdp_key).get("name") == name_or_id:
                            _pdp = _pdps.json().get("pdps").get(_pdp_key)
                            name_or_id = _pdp_key
                            break
                if not _pdp:
                    raise Exception("Cannot find PDP with name or ID {}".format(name_or_id))
                else:
                    if human:
                        result = {"pdps": {name_or_id: _pdp}}
                    else:
                        result = {"pdps": [{name_or_id: _pdp}]}
            else:
                result = _pdps.json()

            if human:
                return PDPCLI.human_display(result)
            else:
                return result
        LOGGER.error('Cannot list PDP {}'.format(_pdps.status_code))

    @staticmethod
    @hug.object.cli
    def add(name, description="", security_pipeline="", vim_project_id="", human: bool = False):
        """
        Add pdp in the database
        :return: JSON status output
        """
        db_conf = configuration.get_configuration(key='management')
        manager_api_key = connect_from_env()
        security_pipeline = security_pipeline.split(",")
        _pdps = requests.post(
            "{}/pdp".format(db_conf.get("url")),
            json={
                "name": name,
                "security_pipeline": security_pipeline,
                "vim_project_id": vim_project_id,
                "description": description,
            },
            headers={
                "x-api-key": manager_api_key,
                "Content-Type": "application/json"
            }
        )
        if _pdps.status_code == 200:
            LOGGER.warning('Create {}'.format(_pdps.content))
            if human:
                return PDPCLI.human_display(_pdps.json())
            else:
                return _pdps.json()
        LOGGER.error('Cannot create {}'.format(name, _pdps.content[:40]))

    @staticmethod
    @hug.object.cli
    def delete(name='default'):
        db_conf = configuration.get_configuration(key='management')
        manager_api_key = connect_from_env()
        _pdps = PDPCLI.list()
        for _slave_id, _slave_value in _pdps.get("pdps").items():
            if _slave_value.get("name") == name:
                req = requests.delete(
                    "{}/pdp/{}".format(db_conf.get("url"), _slave_id),
                    headers={"x-api-key": manager_api_key}
                )
                break
        else:
            LOGGER.error("Cannot find PDP with name {}".format(name))
            return False
        if req.status_code == 200:
            LOGGER.warning('Deleted {}'.format(name))
            return True
        LOGGER.error("Cannot delete PDP with name {}".format(name))
        return False

    @staticmethod
    @hug.object.cli
    def update(name, description=None, security_pipeline=None, vim_project_id=None):
        db_conf = configuration.get_configuration(key='management')
        manager_api_key = connect_from_env()
        _pdps = PDPCLI.list()

        for _slave_id, _slave_value in _pdps.get("pdps").items():
            if _slave_value.get("name") == name:
                description_updated = _slave_value.get("description")
                security_pipeline_updated = _slave_value.get("security_pipeline")
                vim_project_id_updated = _slave_value.get("vim_project_id")

                if description is not None:
                    description_updated = description
                if security_pipeline is not None:
                    if security_pipeline == "":
                        LOGGER.error(f"Policy given to update the PDP {name} is unknown")
                        return
                    else:
                        security_pipeline_updated = security_pipeline.split(",")
                if vim_project_id is not None:
                    vim_project_id_updated = vim_project_id

                req = requests.patch(
                    "{}/pdp/{}".format(db_conf.get("url"), _slave_id),
                    json={
                        "name": name,
                        "security_pipeline": security_pipeline_updated,
                        "vim_project_id": vim_project_id_updated,
                        "description": description_updated,
                    },
                    headers={
                        "x-api-key": manager_api_key,
                        "Content-Type": "application/json"
                    }
                )

        if req.status_code == 200:
            LOGGER.warning('Updated {}'.format(name))
            return True
        LOGGER.error('Cannot update PDP {}'.format(req.status_code))
        return False

    @staticmethod
    def human_display(pdps_json):
        human_result = "PDPs"
        for pdp in pdps_json.get("pdps"):
            human_result += "\n" + pdps_json.get("pdps").get(pdp).get("name") + " : \n"
            human_result += "\tname : " + pdps_json.get("pdps").get(pdp).get("name") + "\n"
            human_result += "\tid : " + pdp + "\n"
            human_result += "\tdescription : " + pdps_json.get("pdps").get(pdp).get("description") + "\n"
            human_result += "\tvim_project_id : " + pdps_json.get("pdps").get(pdp).get("vim_project_id") + "\n"
            human_result += "\tsecurity_pipeline : \n"
            for security_pipeline in pdps_json.get("pdps").get(pdp).get("security_pipeline"):
                human_result += "\t\t" + security_pipeline + "\n"
        return human_result

    # FIXME: not tested
    # @staticmethod
    # @hug.object.cli
    # def set_project(pdp_name, project_id):
    #     db_conf = configuration.get_configuration(key='management')
    #     manager_api_key = configuration.get_api_key_for_user("admin")
    #     _pdp = PDPCLI.get(pdp_name)
    #     _pdp_id = list(_pdp.get("pdps")[0].keys())[0]
    #     _pdp_name = _pdp.get("pdps")[0].get(_pdp_id).get("name")
    #     _pdps = requests.patch(
    #         "{}/pdp/{}".format(db_conf.get("url"), _pdp_id),
    #         json={
    #             "name": _pdp_name,
    #             "vim_project_id": project_id,
    #         },
    #         headers={
    #             "x-api-key": manager_api_key,
    #             "Content-Type": "application/json"
    #         }
    #     )
    #     if _pdps.status_code == 200:
    #         LOGGER.warning('Set project {}'.format(_pdps.content))
    #         return _pdps.json()
    #     LOGGER.error('Cannot set project {} (error: {})'.format(project_id, _pdps.status_code))
    #     return 'Cannot set project {} (error: {})'.format(project_id, _pdps.status_code)
    #
    # @staticmethod
    # @hug.object.cli
    # def add_pipeline(pdp_name, pipeline_id):
    #     db_conf = configuration.get_configuration(key='management')
    #     manager_api_key = configuration.get_api_key_for_user("admin")
    #     _pdp = PDPCLI.get(pdp_name)
    #     _pdp_id = list(_pdp.get("pdps")[0].keys())[0]
    #     _pdp_name = _pdp.get("pdps")[0].get(_pdp_id).get("name")
    #     _pdp_pipelines = _pdp.get("pdps")[0].get(_pdp_id).get("security_pipeline", [])
    #     # TODO check if pipeline exists
    #     _pdp_pipelines.append(pipeline_id)
    #     _pdps = requests.patch(
    #         "{}/pdp/{}".format(db_conf.get("url"), _pdp_id),
    #         json={
    #             "name": _pdp_name,
    #             "security_pipeline": _pdp_pipelines,
    #         },
    #         headers={
    #             "x-api-key": manager_api_key,
    #             "Content-Type": "application/json"
    #         }
    #     )
    #     if _pdps.status_code == 200:
    #         LOGGER.warning('Set project {}'.format(_pdps.content))
    #         return _pdps.json()
    #     LOGGER.error('Cannot add security pipeline {} (error: {})'.format(pipeline_id,
    #                                                                       _pdps.status_code))
    #     return 'Cannot add security pipeline {} (error: {})'.format(pipeline_id, _pdps.content)
    #
    # @staticmethod
    # @hug.object.cli
    # def delete_pipeline(pdp_name, pipeline_id):
    #     db_conf = configuration.get_configuration(key='management')
    #     manager_api_key = configuration.get_api_key_for_user("admin")
    #     _pdp = PDPCLI.get(pdp_name)
    #     _pdp_id = list(_pdp.get("pdps")[0].keys())[0]
    #     _pdp_name = _pdp.get("pdps")[0].get(_pdp_id).get("name")
    #     _pdp_pipelines = _pdp.get("pdps")[0].get(_pdp_id).get("security_pipeline")
    #     # TODO check if pipeline exists
    #     _pdp_pipelines.remove(pipeline_id)
    #     _pdps = requests.patch(
    #         "{}/pdp/{}".format(db_conf.get("url"), _pdp_id),
    #         json={
    #             "name": _pdp_name,
    #             "security_pipeline": _pdp_pipelines,
    #         },
    #         headers={
    #             "x-api-key": manager_api_key,
    #             "Content-Type": "application/json"
    #         }
    #     )
    #     if _pdps.status_code == 200:
    #         LOGGER.warning('Set project {}'.format(_pdps.content))
    #         return _pdps.json()
    #     LOGGER.error('Cannot add security pipeline {} (error: {})'.format(pipeline_id,
    #                                                                       _pdps.status_code))
    #     return 'Cannot add security pipeline {} (error: {})'.format(pipeline_id, _pdps.status_code)