Projekt

Obecné

Profil

Stáhnout (29.3 KB) Statistiky
| Větev: | Tag: | Revize:
1
import json
2
from datetime import datetime
3
from itertools import chain
4
from json import JSONDecodeError
5

    
6
from flask import request, Response
7
from injector import inject
8

    
9
from src.constants import CA_ID, \
10
    SSL_ID, SIGNATURE_ID, AUTHENTICATION_ID, \
11
    DATETIME_FORMAT, ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID  # TODO DATABASE_FILE - not the Controller's
12
from src.controllers.return_codes import *
13
from src.exceptions.database_exception import DatabaseException
14
from src.exceptions.unknown_exception import UnknownException
15
from src.model.subject import Subject
16
from src.services.certificate_service import CertificateService, RevocationReasonInvalidException, \
17
    CertificateStatusInvalidException, CertificateNotFoundException, CertificateAlreadyRevokedException, \
18
    CertificateCannotBeSetToValid
19
#  responsibility.
20
from src.services.key_service import KeyService
21
from src.utils.logger import Logger
22
from src.utils.util import dict_to_string
23

    
24
TREE_NODE_TYPE_COUNT = 3
25

    
26
FILTERING = "filtering"
27
ISSUER = "issuer"
28
US = "usage"
29
NOT_AFTER = "notAfter"
30
NOT_BEFORE = "notBefore"
31
COMMON_NAME = "CN"
32
ID = "id"
33
USAGE = "usage"
34
SUBJECT = "subject"
35
VALIDITY_DAYS = "validityDays"
36
CA = "CA"
37
ISSUED_BY = "issuedby"
38
STATUS = "status"
39
REASON = "reason"
40
REASON_UNDEFINED = "unspecified"
41
NAME = "name"
42
PASSWORD = "password"
43

    
44
E_NO_ISSUER_FOUND = {"success": False, "data": "No certificate authority with such unique ID exists."}
45
E_NO_CERTIFICATES_FOUND = {"success": False, "data": "No such certificate found."}
46
E_NO_CERTIFICATE_ALREADY_REVOKED = {"success": False, "data": "Certificate is already revoked."}
47
E_NO_CERT_PRIVATE_KEY_FOUND = {"success": False,
48
                               "data": "Internal server error (certificate's private key cannot be found)."}
49
E_NOT_JSON_FORMAT = {"success": False, "data": "The request must be JSON-formatted."}
50
E_CORRUPTED_DATABASE = {"success": False, "data": "Internal server error (corrupted database)."}
51
E_GENERAL_ERROR = {"success": False, "data": "Internal server error (unknown origin)."}
52
E_MISSING_PARAMETERS = {"success": False, "data": "Invalid request, missing parameters."}
53
E_WRONG_PARAMETERS = {"success": False, "data": "Invalid request, wrong parameters."}
54
E_IDENTITY_NAME_NOT_SPECIFIED = {"success": False, "data": "Invalid request, missing identity name."}
55
E_IDENTITY_PASSWORD_NOT_SPECIFIED = {"success": False, "data": "Invalid request, missing identity password."}
56

    
57

    
58
class CertController:
59
    KEY_MAP = {'CA': CA_ID, 'SSL': SSL_ID, 'digitalSignature': SIGNATURE_ID, 'authentication': AUTHENTICATION_ID}
60
    INVERSE_KEY_MAP = {k: v for v, k in KEY_MAP.items()}
61

    
62
    @inject
63
    def __init__(self, certificate_service: CertificateService, key_service: KeyService):
64
        self.certificate_service = certificate_service
65
        self.key_service = key_service
66

    
67
    def create_certificate(self):
68
        """create new certificate
69

    
70
        Create a new certificate based on given information
71

    
72
        :param body: Certificate data to be created
73
        :type body: dict | bytes
74

    
75
        :rtype: CreatedResponse
76
        """
77

    
78
        Logger.info(f"\n\t{request.referrer}"
79
                    f"\n\t{request.method}   {request.path}   {request.scheme}")
80

    
81
        required_keys = {SUBJECT, USAGE, VALIDITY_DAYS}                             # required fields of the POST req
82

    
83
        if request.is_json:                                                         # accept JSON only
84
            body = request.get_json()
85

    
86
            Logger.info(f"\n\tRequest body:"
87
                        f"\n{dict_to_string(body)}")
88

    
89
            if not all(k in body for k in required_keys):                           # verify that all keys are present
90
                Logger.error(f"Invalid request, missing parameters")
91
                return E_MISSING_PARAMETERS, C_BAD_REQUEST
92

    
93
            if not isinstance(body[VALIDITY_DAYS], int):                            # type checking
94
                Logger.error(f"Invalid request, wrong parameter '{VALIDITY_DAYS}'.")
95
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
96

    
97
            subject = Subject.from_dict(body[SUBJECT])                              # generate Subject from passed dict
98

    
99
            if subject is None:                                                     # if the format is incorrect
100
                Logger.error(f"Invalid request, wrong parameter '{SUBJECT}'.")
101
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
102

    
103
            usages_dict = {}
104

    
105
            if not isinstance(body[USAGE], dict):                                   # type checking
106
                Logger.error(f"Invalid request, wrong parameter '{USAGE}'.")
107
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
108

    
109
            for k, v in body[USAGE].items():                                        # for each usage
110
                if k not in CertController.KEY_MAP:                                 # check that it is a valid usage
111
                    Logger.error(f"Invalid request, wrong parameter '{USAGE}'[{k}].")
112
                    return E_WRONG_PARAMETERS, C_BAD_REQUEST                        # and throw if it is not
113
                usages_dict[CertController.KEY_MAP[k]] = v                          # otherwise translate key and set
114

    
115
            key = self.key_service.create_new_key()                                      # TODO pass key
116

    
117
            if CA not in body or body[CA] is None:                                  # if issuer omitted (legal) or none
118
                cert = self.certificate_service.create_root_ca(                          # create a root CA
119
                    key,
120
                    subject,
121
                    usages=usages_dict,                                             # TODO ignoring usages -> discussion
122
                    days=body[VALIDITY_DAYS]
123
                )
124
            else:
125
                issuer = self.certificate_service.get_certificate(body[CA])              # get base issuer info
126

    
127
                if issuer is None:                                                  # if such issuer does not exist
128
                    Logger.error(f"No certificate authority with such unique ID exists 'ID = {key.private_key_id}'.")
129
                    self.key_service.delete_key(key.private_key_id)                      # free
130
                    return E_NO_ISSUER_FOUND, C_BAD_REQUEST                         # and throw
131

    
132
                issuer_key = self.key_service.get_key(issuer.private_key_id)             # get issuer's key, which must exist
133

    
134
                if issuer_key is None:                                              # if it does not
135
                    Logger.error(f"Internal server error (corrupted database).")
136
                    self.key_service.delete_key(key.private_key_id)                      # free
137
                    return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR            # and throw
138

    
139
                f = self.certificate_service.create_ca if CA_ID in usages_dict and usages_dict[CA_ID] else \
140
                    self.certificate_service.create_end_cert
141

    
142
                # noinspection PyTypeChecker
143
                cert = f(                                                           # create inter CA or end cert
144
                    key,                                                            # according to whether 'CA' is among
145
                    subject,                                                        # the usages' fields
146
                    issuer,
147
                    issuer_key,
148
                    usages=usages_dict,
149
                    days=body[VALIDITY_DAYS]
150
                )
151

    
152
            if cert is not None:
153
                return {"success": True,
154
                        "data": cert.certificate_id}, C_CREATED_SUCCESSFULLY
155
            else:                                                                   # if this fails, then
156
                Logger.error(f"Internal error: The certificate could not have been created.")
157
                self.key_service.delete_key(key.private_key_id)                          # free
158
                return {"success": False,                                           # and wonder what the cause is,
159
                        "data": "Internal error: The certificate could not have been created."}, C_BAD_REQUEST
160
                                                                                    # as obj/None carries only one bit
161
                                                                                    # of error information
162
        else:
163
            Logger.error(f"The request must be JSON-formatted.")
164
            return E_NOT_JSON_FORMAT, C_BAD_REQUEST                                 # throw in case of non-JSON format
165

    
166
    def get_certificate_by_id(self, id):
167
        """get certificate by ID
168

    
169
        Get certificate in PEM format by ID
170

    
171
        :param id: ID of a certificate to be queried
172
        :type id: dict | bytes
173

    
174
        :rtype: PemResponse
175
        """
176

    
177
        Logger.info(f"\n\t{request.referrer}"
178
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
179
                    f"\n\tCertificate ID = {id}")
180
        try:
181
            v = int(id)
182
        except ValueError:
183
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
184
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
185

    
186
        cert = self.certificate_service.get_certificate(v)
187

    
188
        if cert is None:
189
            Logger.error(f"No such certificate found 'ID = {v}'.")
190
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
191
        else:
192
            return {"success": True, "data": cert.pem_data}, C_SUCCESS
193

    
194
    def get_certificate_details_by_id(self, id):
195
        """get certificate's details by ID
196

    
197
        Get certificate details by ID
198

    
199
        :param id: ID of a certificate whose details are to be queried
200
        :type id: dict | bytes
201

    
202
        :rtype: CertificateResponse
203
        """
204

    
205
        Logger.info(f"\n\t{request.referrer}"
206
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
207
                    f"\n\tCertificate ID = {id}")
208

    
209
        try:
210
            v = int(id)
211
        except ValueError:
212
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
213
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
214

    
215
        cert = self.certificate_service.get_certificate(v)
216

    
217
        if cert is None:
218
            Logger.error(f"No such certificate found 'ID = {v}'.")
219
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
220

    
221
        data = self.cert_to_dict_full(cert)
222
        if data is None:
223
            return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
224

    
225
        try:
226
            state = self.certificate_service.get_certificate_state(v)
227
            data["status"] = state
228
        except CertificateNotFoundException:
229
            Logger.error(f"No such certificate found 'ID = {id}'.")
230

    
231
        return {"success": True, "data": data}, C_SUCCESS
232

    
233
    def get_certificate_list(self):
234
        """get list of certificates
235

    
236
        Lists certificates based on provided filtering options
237

    
238
        :param filtering: Filter certificate type to be queried
239
        :type filtering: dict | bytes
240

    
241
        :rtype: CertificateListResponse
242
        """
243

    
244
        Logger.info(f"\n\t{request.referrer}"
245
                    f"\n\t{request.method}   {request.path}   {request.scheme}")
246

    
247
        targets = {ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID}                  # all targets
248
        issuer_id = -1
249

    
250
        # the filtering parameter can be read as URL argument or as a request body
251
        if request.is_json or FILTERING in request.args.keys():                     # if the request carries JSON data
252
            if request.is_json:
253
                data = request.get_json()                                           # get it
254
            else:
255
                try:
256
                    data = {FILTERING: json.loads(request.args[FILTERING])}
257
                except JSONDecodeError:
258
                    Logger.error(f"The request must be JSON-formatted.")
259
                    return E_NOT_JSON_FORMAT, C_BAD_REQUEST
260

    
261
            Logger.info(f"\n\tRequest body:"
262
                        f"\n{dict_to_string(data)}")
263

    
264
            if FILTERING in data:                                                   # if the 'filtering' field exists
265
                if isinstance(data[FILTERING], dict):                               # and it is also a 'dict'
266
                    if CA in data[FILTERING]:                                       # containing 'CA'
267
                        if isinstance(data[FILTERING][CA], bool):                   # which is a 'bool',
268
                            if data[FILTERING][CA]:                                 # then filter according to 'CA'.
269
                                targets.remove(CERTIFICATE_ID)
270
                            else:
271
                                targets.remove(ROOT_CA_ID)
272
                                targets.remove(INTERMEDIATE_CA_ID)
273
                        else:
274
                            Logger.error(f"Invalid request, wrong parameters '{FILTERING}.{CA}'.")
275
                            return E_WRONG_PARAMETERS, C_BAD_REQUEST
276
                    if ISSUED_BY in data[FILTERING]:                                # containing 'issuedby'
277
                        if isinstance(data[FILTERING][ISSUED_BY], int):             # which is an 'int'
278
                            issuer_id = data[FILTERING][ISSUED_BY]                  # then get its children only
279
                else:
280
                    Logger.error(f"Invalid request, wrong parameters '{FILTERING}'.")
281
                    return E_WRONG_PARAMETERS, C_BAD_REQUEST
282
            if issuer_id >= 0:                                                      # if filtering by an issuer
283
                try:
284
                    children = self.certificate_service.get_certificates_issued_by(issuer_id)  # get his children
285
                except CertificateNotFoundException:                                # if id does not exist
286
                    Logger.error(f"No such certificate found 'ID = {issuer_id}'.")
287
                    return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND                     # throw
288

    
289
                certs = [child for child in children if child.type_id in targets]
290

    
291
            elif len(targets) == TREE_NODE_TYPE_COUNT:                              # = 3 -> root node,
292
                                                                                    # intermediate node,
293
                                                                                    # or leaf node
294

    
295
                                                                                    # if filtering did not change the
296
                                                                                    # targets,
297
                certs = self.certificate_service.get_certificates()                 # fetch everything
298
            else:                                                                   # otherwise fetch targets only
299
                certs = list(chain(*(self.certificate_service.get_certificates(target) for target in targets)))
300
        else:
301
            certs = self.certificate_service.get_certificates()                     # if no params, fetch everything
302

    
303
        if certs is None:
304
            Logger.error(f"Internal server error (unknown origin).")
305
            return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR
306
        elif len(certs) == 0:
307
            # TODO check log level
308
            Logger.warning(f"No such certificate found (empty list).")
309
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
310
        else:
311
            ret = []
312
            for c in certs:
313
                data = self.cert_to_dict_partial(c)
314
                if data is None:
315
                    Logger.error(f"Internal server error (corrupted database).")
316
                    return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
317
                ret.append(
318
                    data
319
                )
320
            return {"success": True, "data": ret}, C_SUCCESS
321

    
322
    def get_certificate_root_by_id(self, id):
323
        """get certificate's root of trust chain by ID
324

    
325
        Get certificate's root of trust chain in PEM format by ID
326

    
327
        :param id: ID of a child certificate whose root is to be queried
328
        :type id: dict | bytes
329

    
330
        :rtype: PemResponse
331
        """
332

    
333
        Logger.info(f"\n\t{request.referrer}"
334
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
335
                    f"\n\tCertificate ID = {id}")
336

    
337
        try:
338
            v = int(id)
339
        except ValueError:
340
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
341
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
342

    
343
        cert = self.certificate_service.get_certificate(v)
344

    
345
        if cert is None:
346
            Logger.error(f"No such certificate found 'ID = {v}'.")
347
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
348

    
349
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
350
        if trust_chain is None or len(trust_chain) == 0:
351
            Logger.error(f"No such certificate found (empty list).")
352
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
353

    
354
        return {"success": True, "data": trust_chain[-1].pem_data}, C_SUCCESS
355

    
356
    def get_certificate_trust_chain_by_id(self, id):
357
        """get certificate's trust chain by ID (including root certificate)
358

    
359
        Get certificate trust chain in PEM format by ID
360

    
361
        :param id: ID of a child certificate whose chain is to be queried
362
        :type id: dict | bytes
363

    
364
        :rtype: PemResponse
365
        """
366

    
367
        Logger.info(f"\n\t{request.referrer}"
368
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
369
                    f"\n\tCertificate ID = {id}")
370

    
371
        try:
372
            v = int(id)
373
        except ValueError:
374
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
375
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
376

    
377
        cert = self.certificate_service.get_certificate(v)
378

    
379
        if cert is None:
380
            Logger.error(f"No such certificate found 'ID = {v}'.")
381
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
382

    
383
        if cert.parent_id is None:
384
            Logger.error(f"Parent ID is empty in certificate 'ID = {v}'.")
385
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
386

    
387
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
388

    
389
        ret = []
390
        for intermediate in trust_chain:
391
            ret.append(intermediate.pem_data)
392

    
393
        return {"success": True, "data": "".join(ret)}, C_SUCCESS
394

    
395
    def set_certificate_status(self, id):
396
        """
397
        Revoke a certificate given by ID
398
            - revocation request may contain revocation reason
399
            - revocation reason is verified based on the possible predefined values
400
            - if revocation reason is not specified 'undefined' value is used
401
        :param id: Identifier of the certificate to be revoked
402
        :type id: int
403

    
404
        :rtype: SuccessResponse | ErrorResponse (see OpenAPI definition)
405
        """
406

    
407
        Logger.info(f"\n\t{request.referrer}"
408
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
409
                    f"\n\tCertificate ID = {id}")
410

    
411
        required_keys = {STATUS}  # required keys
412

    
413
        # check if the request contains a JSON body
414
        if request.is_json:
415
            request_body = request.get_json()
416

    
417
            Logger.info(f"\n\tRequest body:"
418
                        f"\n{dict_to_string(request_body)}")
419

    
420
            # try to parse certificate identifier -> if it is not int return error 400
421
            try:
422
                identifier = int(id)
423
            except ValueError:
424
                Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
425
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
426

    
427
            # verify that all required keys are present
428
            if not all(k in request_body for k in required_keys):
429
                Logger.error(f"Invalid request, missing parameters.")
430
                return E_MISSING_PARAMETERS, C_BAD_REQUEST
431

    
432
            # get status and reason from the request
433
            status = request_body[STATUS]
434
            reason = request_body.get(REASON, REASON_UNDEFINED)
435
            try:
436
                # set certificate status using certificate_service
437
                self.certificate_service.set_certificate_revocation_status(identifier, status, reason)
438
            except (RevocationReasonInvalidException, CertificateStatusInvalidException):
439
                # these exceptions are thrown in case invalid status or revocation reason is passed to the controller
440
                Logger.error(f"Invalid request, wrong parameters.")
441
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
442
            except CertificateAlreadyRevokedException:
443
                Logger.error(f"Certificate is already revoked 'ID = {identifier}'.")
444
                return E_NO_CERTIFICATE_ALREADY_REVOKED, C_BAD_REQUEST
445
            except CertificateNotFoundException:
446
                Logger.error(f"No such certificate found 'ID = {identifier}'.")
447
                return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
448
            except CertificateCannotBeSetToValid as e:
449
                return {"success": False, "data": str(e)}, C_BAD_REQUEST
450
            return {"success": True,
451
                    "data": "Certificate status updated successfully."}, C_SUCCESS
452
        # throw an error in case the request does not contain a json body
453
        else:
454
            Logger.error(f"The request must be JSON-formatted.")
455
            return E_NOT_JSON_FORMAT, C_BAD_REQUEST
456

    
457
    def cert_to_dict_partial(self, c):
458
        """
459
        Dictionarizes a certificate directly fetched from the database. Contains partial information.
460
        :param c: target cert
461
        :return: certificate dict (compliant with some parts of the REST API)
462
        """
463

    
464
        # TODO check log
465
        Logger.debug(f"Function launched.")
466

    
467
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
468
        if c_issuer is None:
469
            return None
470

    
471
        return {
472
            ID: c.certificate_id,
473
            COMMON_NAME: c.common_name,
474
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
475
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
476
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
477
            ISSUER: {
478
                ID: c_issuer.certificate_id,
479
                COMMON_NAME: c_issuer.common_name
480
            }
481
        }
482

    
483
    def cert_to_dict_full(self, c):
484
        """
485
        Dictionarizes a certificate directly fetched from the database, but adds subject info.
486
        Contains full information.
487
        :param c: target cert
488
        :return: certificate dict (compliant with some parts of the REST API)
489
        """
490

    
491
        Logger.info(f"Function launched.")
492

    
493
        subj = self.certificate_service.get_subject_from_certificate(c)
494
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
495
        if c_issuer is None:
496
            return None
497

    
498
        return {
499
            SUBJECT: subj.to_dict(),
500
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
501
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
502
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
503
            CA: c_issuer.certificate_id
504
        }
505

    
506
    def get_private_key_of_a_certificate(self, id):
507
        """
508
        Get a private key used to sign a certificate in PEM format specified by certificate's ID
509

    
510
        :param id: ID of a certificate whose private key is to be queried
511
        :type id: dict | bytes
512

    
513
        :rtype: PemResponse
514
        """
515

    
516
        Logger.info(f"\n\t{request.referrer}"
517
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
518
                    f"\n\tCertificate ID = {id}")
519

    
520
        # try to parse the supplied ID
521
        try:
522
            v = int(id)
523
        except ValueError:
524
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
525
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
526

    
527
        # find a certificate using the given ID
528
        cert = self.certificate_service.get_certificate(v)
529

    
530
        if cert is None:
531
            Logger.error(f"No such certificate found 'ID = {v}'.")
532
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
533
        else:
534
            # certificate exists, fetch it's private key
535
            private_key = self.key_service.get_key(cert.private_key_id)
536
            if cert is None:
537
                Logger.error(f"Internal server error (certificate's private key cannot be found).")
538
                return E_NO_CERT_PRIVATE_KEY_FOUND, C_INTERNAL_SERVER_ERROR
539
            else:
540
                return {"success": True, "data": private_key.private_key}, C_SUCCESS
541

    
542
    def get_public_key_of_a_certificate(self, id):
543
        """
544
        Get a public key of a certificate in PEM format specified by certificate's ID
545

    
546
        :param id: ID of a certificate whose public key is to be queried
547
        :type id: dict | bytes
548

    
549
        :rtype: PemResponse
550
        """
551

    
552
        Logger.info(f"\n\t{request.referrer}"
553
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
554
                    f"\n\tCertificate ID = {id}")
555

    
556
        # try to parse the supplied ID
557
        try:
558
            v = int(id)
559
        except ValueError:
560
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
561
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
562

    
563
        # find a certificate using the given ID
564
        cert = self.certificate_service.get_certificate(v)
565

    
566
        if cert is None:
567
            Logger.error(f"No such certificate found 'ID = {v}'.")
568
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
569
        else:
570
            return {"success": True, "data": self.certificate_service.get_public_key_from_certificate(cert)}, C_SUCCESS
571

    
572
    def delete_certificate(self, id):
573
        """
574
        Deletes a certificate identified by ID, including its corresponding subtree (all descendants).
575
        :param id: target certificate ID
576
        :rtype: DeleteResponse
577
        """
578

    
579
        Logger.info(f"\n\t{request.referrer}"
580
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
581
                    f"\n\tCertificate ID = {id}")
582

    
583
        try:
584
            v = int(id)
585
        except ValueError:
586
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
587
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
588

    
589
        try:
590
            self.certificate_service.delete_certificate(v)
591
        except CertificateNotFoundException:
592
            Logger.error(f"No such certificate found 'ID = {v}'.")
593
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
594
        except DatabaseException:
595
            Logger.error(f"Internal server error (corrupted database).")
596
            return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
597
        except CertificateStatusInvalidException or RevocationReasonInvalidException or UnknownException:
598
            Logger.error(f"Internal server error (unknown origin).")
599
            return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR
600

    
601
        return {"success": True, "data": "The certificate and its descendants have been successfully deleted."}
602

    
603
    def generate_certificate_pkcs_identity(self, id):
604
        """
605
        Generates a PKCS12 identity (including the chain of trust) of the certificate given by the specified ID.
606
        Response is of application/x-pkcs12 type.
607

    
608
        :param id: ID of a certificate whose PKCS12 identity should be generated
609
        :type id: int
610

    
611
        :rtype: Response
612
        """
613

    
614
        Logger.info(f"\n\t{request.referrer}"
615
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
616
                    f"\n\tCertificate ID = {id}")
617

    
618
        # try to parse the supplied ID
619
        try:
620
            v = int(id)
621
        except ValueError:
622
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}] (expected integer).")
623
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
624

    
625
        # find a certificate using the given ID
626
        cert = self.certificate_service.get_certificate(v)
627

    
628
        if request.is_json:                                                         # accept JSON only
629
            body = request.get_json()
630

    
631
            # check whether the request is well formed meaning that it contains all required fields
632
            if NAME not in body.keys():
633
                return E_IDENTITY_NAME_NOT_SPECIFIED, C_BAD_REQUEST
634

    
635
            if PASSWORD not in body.keys():
636
                return E_IDENTITY_PASSWORD_NOT_SPECIFIED, C_BAD_REQUEST
637

    
638
            # parse required fields from the request
639
            identity_name = body[NAME]
640
            identity_password = body[PASSWORD]
641

    
642
            # check whether a certificated specified by the given ID exists
643
            if cert is None:
644
                Logger.error(f"No such certificate found 'ID = {v}'.")
645
                return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
646
            else:
647
                # try to load it's private key
648
                key = self.key_service.get_key(cert.private_key_id)
649
                if key is None:
650
                    Logger.error(
651
                        f"The private key 'ID = {cert.private_key_id}'of the certificate 'ID = {cert.certificate_id}' does not exist.")
652
                    return E_NO_CERTIFICATES_FOUND, C_INTERNAL_SERVER_ERROR
653
                else:
654
                    # generate PKCS12 identity
655
                    identity_byte_array = self.certificate_service.generate_pkcs_identity(cert, key,
656
                                                                                          identity_name,
657
                                                                                          identity_password)
658
                    return Response(identity_byte_array, mimetype='application/x-pkcs12')
(2-2/4)