Projekt

Obecné

Profil

Stáhnout (28.1 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
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.cryptography import CryptographyException
21
from src.services.key_service import KeyService
22
from src.utils.logger import Logger
23
from src.utils.util import dict_to_string
24

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

    
45
E_NO_ISSUER_FOUND = {"success": False, "data": "No certificate authority with such unique ID exists."}
46
E_NO_CERTIFICATES_FOUND = {"success": False, "data": "No such certificate found."}
47
E_NO_CERTIFICATE_ALREADY_REVOKED = {"success": False, "data": "Certificate is already revoked."}
48
E_NO_CERT_PRIVATE_KEY_FOUND = {"success": False,
49
                               "data": "Internal server error (certificate's private key cannot be found)."}
50
E_NOT_JSON_FORMAT = {"success": False, "data": "The request must be JSON-formatted."}
51
E_CORRUPTED_DATABASE = {"success": False, "data": "Internal server error (corrupted database)."}
52
E_GENERAL_ERROR = {"success": False, "data": "Internal server error (unknown origin)."}
53
E_MISSING_PARAMETERS = {"success": False, "data": "Invalid request, missing parameters."}
54
E_WRONG_PARAMETERS = {"success": False, "data": "Invalid request, wrong parameters."}
55
E_WRONG_PASSWORD = {"success": False, "data": "The provided passphrase does not match the provided key."}
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 USAGE not in body or not isinstance(body[USAGE], list):              # type checking
106
                Logger.error(f"Invalid request, wrong parameter '{USAGE}'.")
107
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
108

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

    
115
            if KEY in body:
116
                if isinstance(body[KEY], dict):
117
                    if PASSWORD in body[KEY]:
118
                        passphrase = body[KEY][PASSWORD]
119
                        if KEY_PEM in body[KEY]:
120
                            key_pem = body[KEY][KEY_PEM]
121
                            if not self.key_service.verify_key(key_pem, passphrase=passphrase):
122
                                Logger.error(f"Passphrase specified but invalid.")
123
                                return E_WRONG_PASSWORD, C_BAD_REQUEST
124
                            key = self.key_service.wrap_custom_key(key_pem, passphrase=passphrase)
125
                        else:
126
                            key = self.key_service.create_new_key(passphrase)
127
                    else:
128
                        if KEY_PEM in body[KEY]:
129
                            key_pem = body[KEY][KEY_PEM]
130
                            if not self.key_service.verify_key(key_pem, passphrase=None):
131
                                Logger.error("Passphrase ommited but required.")
132
                                return E_WRONG_PASSWORD, C_BAD_REQUEST
133
                            key = self.key_service.wrap_custom_key(key_pem, passphrase=None)
134
                        else:
135
                            return E_WRONG_PARAMETERS, C_BAD_REQUEST                # if "key" exists but is empty
136
                else:
137
                    return E_WRONG_PARAMETERS, C_BAD_REQUEST
138
            else:
139
                key = self.key_service.create_new_key()                             # if "key" does not exist
140

    
141
            if CA not in body or body[CA] is None:                                  # if issuer omitted (legal) or none
142
                cert = self.certificate_service.create_root_ca(                     # create a root CA
143
                    key,
144
                    subject,
145
                    usages=usages_dict,                                             # TODO ignoring usages -> discussion
146
                    days=body[VALIDITY_DAYS]
147
                )
148
            else:
149
                issuer = self.certificate_service.get_certificate(body[CA])         # get base issuer info
150

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

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

    
158
                if issuer_key is None:                                              # if it does not
159
                    Logger.error(f"Internal server error (corrupted database).")
160
                    self.key_service.delete_key(key.private_key_id)                 # free
161
                    return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR            # and throw
162

    
163
                f = self.certificate_service.create_ca if CA_ID in usages_dict and usages_dict[CA_ID] else \
164
                    self.certificate_service.create_end_cert
165

    
166
                # noinspection PyTypeChecker
167
                cert = f(                                                           # create inter CA or end cert
168
                    key,                                                            # according to whether 'CA' is among
169
                    subject,                                                        # the usages' fields
170
                    issuer,
171
                    issuer_key,
172
                    usages=usages_dict,
173
                    days=body[VALIDITY_DAYS]
174
                )
175

    
176
            if cert is not None:
177
                return {"success": True,
178
                        "data": cert.certificate_id}, C_CREATED_SUCCESSFULLY
179
            else:                                                                   # if this fails, then
180
                Logger.error(f"Internal error: The certificate could not have been created.")
181
                self.key_service.delete_key(key.private_key_id)                     # free
182
                return {"success": False,                                           # and wonder what the cause is,
183
                        "data": "Internal error: The certificate could not have been created."}, C_BAD_REQUEST
184
                                                                                    # as obj/None carries only one bit
185
                                                                                    # of error information
186
        else:
187
            Logger.error(f"The request must be JSON-formatted.")
188
            return E_NOT_JSON_FORMAT, C_BAD_REQUEST                                 # throw in case of non-JSON format
189

    
190
    def get_certificate_by_id(self, id):
191
        """get certificate by ID
192

    
193
        Get certificate in PEM format by ID
194

    
195
        :param id: ID of a certificate to be queried
196
        :type id: dict | bytes
197

    
198
        :rtype: PemResponse
199
        """
200

    
201
        Logger.info(f"\n\t{request.referrer}"
202
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
203
                    f"\n\tCertificate ID = {id}")
204
        try:
205
            v = int(id)
206
        except ValueError:
207
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
208
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
209

    
210
        cert = self.certificate_service.get_certificate(v)
211

    
212
        if cert is None:
213
            Logger.error(f"No such certificate found 'ID = {v}'.")
214
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
215
        else:
216
            return {"success": True, "data": cert.pem_data}, C_SUCCESS
217

    
218
    def get_certificate_details_by_id(self, id):
219
        """get certificate's details by ID
220

    
221
        Get certificate details by ID
222

    
223
        :param id: ID of a certificate whose details are to be queried
224
        :type id: dict | bytes
225

    
226
        :rtype: CertificateResponse
227
        """
228

    
229
        Logger.info(f"\n\t{request.referrer}"
230
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
231
                    f"\n\tCertificate ID = {id}")
232

    
233
        try:
234
            v = int(id)
235
        except ValueError:
236
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
237
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
238

    
239
        cert = self.certificate_service.get_certificate(v)
240

    
241
        if cert is None:
242
            Logger.error(f"No such certificate found 'ID = {v}'.")
243
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
244

    
245
        data = self.cert_to_dict_full(cert)
246
        if data is None:
247
            return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
248

    
249
        try:
250
            state = self.certificate_service.get_certificate_state(v)
251
            data["status"] = state
252
        except CertificateNotFoundException:
253
            Logger.error(f"No such certificate found 'ID = {id}'.")
254

    
255
        return {"success": True, "data": data}, C_SUCCESS
256

    
257
    def get_certificate_list(self):
258
        """get list of certificates
259

    
260
        Lists certificates based on provided filtering options
261

    
262
        :param filtering: Filter certificate type to be queried
263
        :type filtering: dict | bytes
264

    
265
        :rtype: CertificateListResponse
266
        """
267

    
268
        Logger.info(f"\n\t{request.referrer}"
269
                    f"\n\t{request.method}   {request.path}   {request.scheme}")
270

    
271
        targets = {ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID}                  # all targets
272
        issuer_id = -1
273

    
274
        # the filtering parameter can be read as URL argument or as a request body
275
        if request.is_json or FILTERING in request.args.keys():                     # if the request carries JSON data
276
            if request.is_json:
277
                data = request.get_json()                                           # get it
278
            else:
279
                try:
280
                    data = {FILTERING: json.loads(request.args[FILTERING])}
281
                except JSONDecodeError:
282
                    Logger.error(f"The request must be JSON-formatted.")
283
                    return E_NOT_JSON_FORMAT, C_BAD_REQUEST
284

    
285
            Logger.info(f"\n\tRequest body:"
286
                        f"\n{dict_to_string(data)}")
287

    
288
            if FILTERING in data:                                                   # if the 'filtering' field exists
289
                if isinstance(data[FILTERING], dict):                               # and it is also a 'dict'
290
                    if CA in data[FILTERING]:                                       # containing 'CA'
291
                        if isinstance(data[FILTERING][CA], bool):                   # which is a 'bool',
292
                            if data[FILTERING][CA]:                                 # then filter according to 'CA'.
293
                                targets.remove(CERTIFICATE_ID)
294
                            else:
295
                                targets.remove(ROOT_CA_ID)
296
                                targets.remove(INTERMEDIATE_CA_ID)
297
                        else:
298
                            Logger.error(f"Invalid request, wrong parameters '{FILTERING}.{CA}'.")
299
                            return E_WRONG_PARAMETERS, C_BAD_REQUEST
300
                    if ISSUED_BY in data[FILTERING]:                                # containing 'issuedby'
301
                        if isinstance(data[FILTERING][ISSUED_BY], int):             # which is an 'int'
302
                            issuer_id = data[FILTERING][ISSUED_BY]                  # then get its children only
303
                else:
304
                    Logger.error(f"Invalid request, wrong parameters '{FILTERING}'.")
305
                    return E_WRONG_PARAMETERS, C_BAD_REQUEST
306
            if issuer_id >= 0:                                                      # if filtering by an issuer
307
                try:
308
                    children = self.certificate_service.get_certificates_issued_by(issuer_id)  # get his children
309
                except CertificateNotFoundException:                                # if id does not exist
310
                    Logger.error(f"No such certificate found 'ID = {issuer_id}'.")
311
                    return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND                     # throw
312

    
313
                certs = [child for child in children if child.type_id in targets]
314

    
315
            elif len(targets) == TREE_NODE_TYPE_COUNT:                              # = 3 -> root node,
316
                                                                                    # intermediate node,
317
                                                                                    # or leaf node
318

    
319
                                                                                    # if filtering did not change the
320
                                                                                    # targets,
321
                certs = self.certificate_service.get_certificates()                 # fetch everything
322
            else:                                                                   # otherwise fetch targets only
323
                certs = list(chain(*(self.certificate_service.get_certificates(target) for target in targets)))
324
        else:
325
            certs = self.certificate_service.get_certificates()                     # if no params, fetch everything
326

    
327
        if certs is None:
328
            Logger.error(f"Internal server error (unknown origin).")
329
            return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR
330
        elif len(certs) == 0:
331
            # TODO check log level
332
            Logger.warning(f"No such certificate found (empty list).")
333
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
334
        else:
335
            ret = []
336
            for c in certs:
337
                data = self.cert_to_dict_partial(c)
338
                if data is None:
339
                    Logger.error(f"Internal server error (corrupted database).")
340
                    return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
341
                ret.append(
342
                    data
343
                )
344
            return {"success": True, "data": ret}, C_SUCCESS
345

    
346
    def get_certificate_root_by_id(self, id):
347
        """get certificate's root of trust chain by ID
348

    
349
        Get certificate's root of trust chain in PEM format by ID
350

    
351
        :param id: ID of a child certificate whose root is to be queried
352
        :type id: dict | bytes
353

    
354
        :rtype: PemResponse
355
        """
356

    
357
        Logger.info(f"\n\t{request.referrer}"
358
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
359
                    f"\n\tCertificate ID = {id}")
360

    
361
        try:
362
            v = int(id)
363
        except ValueError:
364
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
365
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
366

    
367
        cert = self.certificate_service.get_certificate(v)
368

    
369
        if cert is None:
370
            Logger.error(f"No such certificate found 'ID = {v}'.")
371
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
372

    
373
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
374
        if trust_chain is None or len(trust_chain) == 0:
375
            Logger.error(f"No such certificate found (empty list).")
376
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
377

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

    
380
    def get_certificate_trust_chain_by_id(self, id):
381
        """get certificate's trust chain by ID (including root certificate)
382

    
383
        Get certificate trust chain in PEM format by ID
384

    
385
        :param id: ID of a child certificate whose chain is to be queried
386
        :type id: dict | bytes
387

    
388
        :rtype: PemResponse
389
        """
390

    
391
        Logger.info(f"\n\t{request.referrer}"
392
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
393
                    f"\n\tCertificate ID = {id}")
394

    
395
        try:
396
            v = int(id)
397
        except ValueError:
398
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
399
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
400

    
401
        cert = self.certificate_service.get_certificate(v)
402

    
403
        if cert is None:
404
            Logger.error(f"No such certificate found 'ID = {v}'.")
405
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
406

    
407
        if cert.parent_id is None:
408
            Logger.error(f"Parent ID is empty in certificate 'ID = {v}'.")
409
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
410

    
411
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
412

    
413
        ret = []
414
        for intermediate in trust_chain:
415
            ret.append(intermediate.pem_data)
416

    
417
        return {"success": True, "data": "".join(ret)}, C_SUCCESS
418

    
419
    def set_certificate_status(self, id):
420
        """
421
        Revoke a certificate given by ID
422
            - revocation request may contain revocation reason
423
            - revocation reason is verified based on the possible predefined values
424
            - if revocation reason is not specified 'undefined' value is used
425
        :param id: Identifier of the certificate to be revoked
426
        :type id: int
427

    
428
        :rtype: SuccessResponse | ErrorResponse (see OpenAPI definition)
429
        """
430

    
431
        Logger.info(f"\n\t{request.referrer}"
432
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
433
                    f"\n\tCertificate ID = {id}")
434

    
435
        required_keys = {STATUS}  # required keys
436

    
437
        # check if the request contains a JSON body
438
        if request.is_json:
439
            request_body = request.get_json()
440

    
441
            Logger.info(f"\n\tRequest body:"
442
                        f"\n{dict_to_string(request_body)}")
443

    
444
            # try to parse certificate identifier -> if it is not int return error 400
445
            try:
446
                identifier = int(id)
447
            except ValueError:
448
                Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
449
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
450

    
451
            # verify that all required keys are present
452
            if not all(k in request_body for k in required_keys):
453
                Logger.error(f"Invalid request, missing parameters.")
454
                return E_MISSING_PARAMETERS, C_BAD_REQUEST
455

    
456
            # get status and reason from the request
457
            status = request_body[STATUS]
458
            reason = request_body.get(REASON, REASON_UNDEFINED)
459
            try:
460
                # set certificate status using certificate_service
461
                self.certificate_service.set_certificate_revocation_status(identifier, status, reason)
462
            except (RevocationReasonInvalidException, CertificateStatusInvalidException):
463
                # these exceptions are thrown in case invalid status or revocation reason is passed to the controller
464
                Logger.error(f"Invalid request, wrong parameters.")
465
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
466
            except CertificateAlreadyRevokedException:
467
                Logger.error(f"Certificate is already revoked 'ID = {identifier}'.")
468
                return E_NO_CERTIFICATE_ALREADY_REVOKED, C_BAD_REQUEST
469
            except CertificateNotFoundException:
470
                Logger.error(f"No such certificate found 'ID = {identifier}'.")
471
                return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
472
            except CertificateCannotBeSetToValid as e:
473
                return {"success": False, "data": str(e)}, C_BAD_REQUEST
474
            return {"success": True,
475
                    "data": "Certificate status updated successfully."}, C_SUCCESS
476
        # throw an error in case the request does not contain a json body
477
        else:
478
            Logger.error(f"The request must be JSON-formatted.")
479
            return E_NOT_JSON_FORMAT, C_BAD_REQUEST
480

    
481
    def cert_to_dict_partial(self, c):
482
        """
483
        Dictionarizes a certificate directly fetched from the database. Contains partial information.
484
        :param c: target cert
485
        :return: certificate dict (compliant with some parts of the REST API)
486
        """
487

    
488
        # TODO check log
489
        Logger.debug(f"Function launched.")
490

    
491
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
492
        if c_issuer is None:
493
            return None
494

    
495
        return {
496
            ID: c.certificate_id,
497
            COMMON_NAME: c.common_name,
498
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
499
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
500
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
501
            ISSUER: {
502
                ID: c_issuer.certificate_id,
503
                COMMON_NAME: c_issuer.common_name
504
            }
505
        }
506

    
507
    def cert_to_dict_full(self, c):
508
        """
509
        Dictionarizes a certificate directly fetched from the database, but adds subject info.
510
        Contains full information.
511
        :param c: target cert
512
        :return: certificate dict (compliant with some parts of the REST API)
513
        """
514

    
515
        Logger.info(f"Function launched.")
516

    
517
        subj = self.certificate_service.get_subject_from_certificate(c)
518
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
519
        if c_issuer is None:
520
            return None
521

    
522
        return {
523
            SUBJECT: subj.to_dict(),
524
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
525
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
526
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
527
            CA: c_issuer.certificate_id
528
        }
529

    
530
    def get_private_key_of_a_certificate(self, id):
531
        """
532
        Get a private key used to sign a certificate in PEM format specified by certificate's ID
533

    
534
        :param id: ID of a certificate whose private key is to be queried
535
        :type id: dict | bytes
536

    
537
        :rtype: PemResponse
538
        """
539

    
540
        Logger.info(f"\n\t{request.referrer}"
541
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
542
                    f"\n\tCertificate ID = {id}")
543

    
544
        # try to parse the supplied ID
545
        try:
546
            v = int(id)
547
        except ValueError:
548
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
549
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
550

    
551
        # find a certificate using the given ID
552
        cert = self.certificate_service.get_certificate(v)
553

    
554
        if cert is None:
555
            Logger.error(f"No such certificate found 'ID = {v}'.")
556
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
557
        else:
558
            # certificate exists, fetch it's private key
559
            private_key = self.key_service.get_key(cert.private_key_id)
560
            if cert is None:
561
                Logger.error(f"Internal server error (certificate's private key cannot be found).")
562
                return E_NO_CERT_PRIVATE_KEY_FOUND, C_INTERNAL_SERVER_ERROR
563
            else:
564
                return {"success": True, "data": private_key.private_key}, C_SUCCESS
565

    
566
    def get_public_key_of_a_certificate(self, id):
567
        """
568
        Get a public key of a certificate in PEM format specified by certificate's ID
569

    
570
        :param id: ID of a certificate whose public key is to be queried
571
        :type id: dict | bytes
572

    
573
        :rtype: PemResponse
574
        """
575

    
576
        Logger.info(f"\n\t{request.referrer}"
577
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
578
                    f"\n\tCertificate ID = {id}")
579

    
580
        # try to parse the supplied ID
581
        try:
582
            v = int(id)
583
        except ValueError:
584
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
585
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
586

    
587
        # find a certificate using the given ID
588
        cert = self.certificate_service.get_certificate(v)
589

    
590
        if cert is None:
591
            Logger.error(f"No such certificate found 'ID = {v}'.")
592
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
593
        else:
594
            return {"success": True, "data": self.certificate_service.get_public_key_from_certificate(cert)}, C_SUCCESS
595

    
596
    def delete_certificate(self, id):
597
        """
598
        Deletes a certificate identified by ID, including its corresponding subtree (all descendants).
599
        :param id: target certificate ID
600
        :rtype: DeleteResponse
601
        """
602

    
603
        Logger.info(f"\n\t{request.referrer}"
604
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
605
                    f"\n\tCertificate ID = {id}")
606

    
607
        try:
608
            v = int(id)
609
        except ValueError:
610
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
611
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
612

    
613
        try:
614
            self.certificate_service.delete_certificate(v)
615
        except CertificateNotFoundException:
616
            Logger.error(f"No such certificate found 'ID = {v}'.")
617
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
618
        except DatabaseException:
619
            Logger.error(f"Internal server error (corrupted database).")
620
            return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
621
        except CertificateStatusInvalidException or RevocationReasonInvalidException or UnknownException:
622
            Logger.error(f"Internal server error (unknown origin).")
623
            return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR
624

    
625
        return {"success": True, "data": "The certificate and its descendants have been successfully deleted."}
(2-2/4)