Projekt

Obecné

Profil

Stáhnout (26.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
#  responsibility.
19
from src.services.key_service import KeyService
20
from src.utils.logger import Logger
21
from src.utils.util import dict_to_string
22

    
23
TREE_NODE_TYPE_COUNT = 3
24

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

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

    
52

    
53
class CertController:
54
    KEY_MAP = {'CA': CA_ID, 'SSL': SSL_ID, 'digitalSignature': SIGNATURE_ID, 'authentication': AUTHENTICATION_ID}
55
    INVERSE_KEY_MAP = {k: v for v, k in KEY_MAP.items()}
56

    
57
    @inject
58
    def __init__(self, certificate_service: CertificateService, key_service: KeyService):
59
        self.certificate_service = certificate_service
60
        self.key_service = key_service
61

    
62
    def create_certificate(self):
63
        """create new certificate
64

    
65
        Create a new certificate based on given information
66

    
67
        :param body: Certificate data to be created
68
        :type body: dict | bytes
69

    
70
        :rtype: CreatedResponse
71
        """
72

    
73
        Logger.info(f"\n\t{request.referrer}"
74
                    f"\n\t{request.method}   {request.path}   {request.scheme}")
75

    
76
        required_keys = {SUBJECT, USAGE, VALIDITY_DAYS}                             # required fields of the POST req
77

    
78
        if request.is_json:                                                         # accept JSON only
79
            body = request.get_json()
80

    
81
            Logger.info(f"\n\tRequest body:"
82
                        f"\n{dict_to_string(body)}")
83

    
84
            if not all(k in body for k in required_keys):                           # verify that all keys are present
85
                Logger.error(f"Invalid request, missing parameters")
86
                return E_MISSING_PARAMETERS, C_BAD_REQUEST
87

    
88
            if not isinstance(body[VALIDITY_DAYS], int):                            # type checking
89
                Logger.error(f"Invalid request, wrong parameter '{VALIDITY_DAYS}'.")
90
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
91

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

    
94
            if subject is None:                                                     # if the format is incorrect
95
                Logger.error(f"Invalid request, wrong parameter '{SUBJECT}'.")
96
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
97

    
98
            usages_dict = {}
99

    
100
            if not isinstance(body[USAGE], dict):                                   # type checking
101
                Logger.error(f"Invalid request, wrong parameter '{USAGE}'.")
102
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
103

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

    
110
            key = self.key_service.create_new_key()                                      # TODO pass key
111

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

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

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

    
129
                if issuer_key is None:                                              # if it does not
130
                    Logger.error(f"Internal server error (corrupted database).")
131
                    self.key_service.delete_key(key.private_key_id)                      # free
132
                    return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR            # and throw
133

    
134
                f = self.certificate_service.create_ca if CA_ID in usages_dict and usages_dict[CA_ID] else \
135
                    self.certificate_service.create_end_cert
136

    
137
                # noinspection PyTypeChecker
138
                cert = f(                                                           # create inter CA or end cert
139
                    key,                                                            # according to whether 'CA' is among
140
                    subject,                                                        # the usages' fields
141
                    issuer,
142
                    issuer_key,
143
                    usages=usages_dict,
144
                    days=body[VALIDITY_DAYS]
145
                )
146

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

    
161
    def get_certificate_by_id(self, id):
162
        """get certificate by ID
163

    
164
        Get certificate in PEM format by ID
165

    
166
        :param id: ID of a certificate to be queried
167
        :type id: dict | bytes
168

    
169
        :rtype: PemResponse
170
        """
171

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

    
181
        cert = self.certificate_service.get_certificate(v)
182

    
183
        if cert is None:
184
            Logger.error(f"No such certificate found 'ID = {v}'.")
185
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
186
        else:
187
            return {"success": True, "data": cert.pem_data}, C_SUCCESS
188

    
189
    def get_certificate_details_by_id(self, id):
190
        """get certificate's details by ID
191

    
192
        Get certificate details by ID
193

    
194
        :param id: ID of a certificate whose details are to be queried
195
        :type id: dict | bytes
196

    
197
        :rtype: CertificateResponse
198
        """
199

    
200
        Logger.info(f"\n\t{request.referrer}"
201
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
202
                    f"\n\tCertificate ID = {id}")
203

    
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
            data = self.cert_to_dict_full(cert)
217
            if data is None:
218
                return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
219
            return {"success": True, "data": data}, C_SUCCESS
220

    
221
    def get_certificate_list(self):
222
        """get list of certificates
223

    
224
        Lists certificates based on provided filtering options
225

    
226
        :param filtering: Filter certificate type to be queried
227
        :type filtering: dict | bytes
228

    
229
        :rtype: CertificateListResponse
230
        """
231

    
232
        Logger.info(f"\n\t{request.referrer}"
233
                    f"\n\t{request.method}   {request.path}   {request.scheme}")
234

    
235
        targets = {ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID}                  # all targets
236
        issuer_id = -1
237

    
238
        # the filtering parameter can be read as URL argument or as a request body
239
        if request.is_json or FILTERING in request.args.keys():                     # if the request carries JSON data
240
            if request.is_json:
241
                data = request.get_json()                                           # get it
242
            else:
243
                try:
244
                    data = {FILTERING: json.loads(request.args[FILTERING])}
245
                except JSONDecodeError:
246
                    Logger.error(f"The request must be JSON-formatted.")
247
                    return E_NOT_JSON_FORMAT, C_BAD_REQUEST
248

    
249
            Logger.info(f"\n\tRequest body:"
250
                        f"\n{dict_to_string(data)}")
251

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

    
277
                certs = [child for child in children if child.type_id in targets]
278

    
279
            elif len(targets) == TREE_NODE_TYPE_COUNT:                              # = 3 -> root node,
280
                                                                                    # intermediate node,
281
                                                                                    # or leaf node
282

    
283
                                                                                    # if filtering did not change the
284
                                                                                    # targets,
285
                certs = self.certificate_service.get_certificates()                 # fetch everything
286
            else:                                                                   # otherwise fetch targets only
287
                certs = list(chain(*(self.certificate_service.get_certificates(target) for target in targets)))
288
        else:
289
            certs = self.certificate_service.get_certificates()                     # if no params, fetch everything
290

    
291
        if certs is None:
292
            Logger.error(f"Internal server error (unknown origin).")
293
            return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR
294
        elif len(certs) == 0:
295
            # TODO check log level
296
            Logger.warning(f"No such certificate found (empty list).")
297
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
298
        else:
299
            ret = []
300
            for c in certs:
301
                data = self.cert_to_dict_partial(c)
302
                if data is None:
303
                    Logger.error(f"Internal server error (corrupted database).")
304
                    return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
305
                ret.append(
306
                    data
307
                )
308
            return {"success": True, "data": ret}, C_SUCCESS
309

    
310
    def get_certificate_root_by_id(self, id):
311
        """get certificate's root of trust chain by ID
312

    
313
        Get certificate's root of trust chain in PEM format by ID
314

    
315
        :param id: ID of a child certificate whose root is to be queried
316
        :type id: dict | bytes
317

    
318
        :rtype: PemResponse
319
        """
320

    
321
        Logger.info(f"\n\t{request.referrer}"
322
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
323
                    f"\n\tCertificate ID = {id}")
324

    
325
        try:
326
            v = int(id)
327
        except ValueError:
328
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
329
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
330

    
331
        cert = self.certificate_service.get_certificate(v)
332

    
333
        if cert is None:
334
            Logger.error(f"No such certificate found 'ID = {v}'.")
335
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
336

    
337
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
338
        if trust_chain is None or len(trust_chain) == 0:
339
            Logger.error(f"No such certificate found (empty list).")
340
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
341

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

    
344
    def get_certificate_trust_chain_by_id(self, id):
345
        """get certificate's trust chain by ID
346

    
347
        Get certificate trust chain in PEM format by ID
348

    
349
        :param id: ID of a child certificate whose chain is to be queried
350
        :type id: dict | bytes
351

    
352
        :rtype: PemResponse
353
        """
354

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

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

    
365
        cert = self.certificate_service.get_certificate(v)
366

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

    
371
        if cert.parent_id is None:
372
            Logger.error(f"Parent ID is empty in certificate 'ID = {v}'.")
373
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
374

    
375
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id)
376

    
377
        ret = []
378
        for intermediate in trust_chain:
379
            ret.append(intermediate.pem_data)
380

    
381
        return {"success": True, "data": "".join(ret)}, C_SUCCESS
382

    
383
    def set_certificate_status(self, id):
384
        """
385
        Revoke a certificate given by ID
386
            - revocation request may contain revocation reason
387
            - revocation reason is verified based on the possible predefined values
388
            - if revocation reason is not specified 'undefined' value is used
389
        :param id: Identifier of the certificate to be revoked
390
        :type id: int
391

    
392
        :rtype: SuccessResponse | ErrorResponse (see OpenAPI definition)
393
        """
394

    
395
        Logger.info(f"\n\t{request.referrer}"
396
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
397
                    f"\n\tCertificate ID = {id}")
398

    
399
        required_keys = {STATUS}  # required keys
400

    
401
        # check if the request contains a JSON body
402
        if request.is_json:
403
            request_body = request.get_json()
404

    
405
            Logger.info(f"\n\tRequest body:"
406
                        f"\n{dict_to_string(request_body)}")
407

    
408
            # try to parse certificate identifier -> if it is not int return error 400
409
            try:
410
                identifier = int(id)
411
            except ValueError:
412
                Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
413
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
414

    
415
            # verify that all required keys are present
416
            if not all(k in request_body for k in required_keys):
417
                Logger.error(f"Invalid request, missing parameters.")
418
                return E_MISSING_PARAMETERS, C_BAD_REQUEST
419

    
420
            # get status and reason from the request
421
            status = request_body[STATUS]
422
            reason = request_body.get(REASON, REASON_UNDEFINED)
423
            try:
424
                # set certificate status using certificate_service
425
                self.certificate_service.set_certificate_revocation_status(identifier, status, reason)
426
            except (RevocationReasonInvalidException, CertificateStatusInvalidException):
427
                # these exceptions are thrown in case invalid status or revocation reason is passed to the controller
428
                Logger.error(f"Invalid request, wrong parameters.")
429
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
430
            except CertificateAlreadyRevokedException:
431
                Logger.error(f"Certificate is already revoked 'ID = {identifier}'.")
432
                return E_NO_CERTIFICATE_ALREADY_REVOKED, C_BAD_REQUEST
433
            except CertificateNotFoundException:
434
                Logger.error(f"No such certificate found 'ID = {identifier}'.")
435
                return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
436
            return {"success": True,
437
                    "data": "Certificate status updated successfully."}, C_SUCCESS
438
        # throw an error in case the request does not contain a json body
439
        else:
440
            Logger.error(f"The request must be JSON-formatted.")
441
            return E_NOT_JSON_FORMAT, C_BAD_REQUEST
442

    
443
    def cert_to_dict_partial(self, c):
444
        """
445
        Dictionarizes a certificate directly fetched from the database. Contains partial information.
446
        :param c: target cert
447
        :return: certificate dict (compliant with some parts of the REST API)
448
        """
449

    
450
        # TODO check log
451
        Logger.debug(f"Function launched.")
452

    
453
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
454
        if c_issuer is None:
455
            return None
456

    
457
        return {
458
            ID: c.certificate_id,
459
            COMMON_NAME: c.common_name,
460
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
461
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
462
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
463
            ISSUER: {
464
                ID: c_issuer.certificate_id,
465
                COMMON_NAME: c_issuer.common_name
466
            }
467
        }
468

    
469
    def cert_to_dict_full(self, c):
470
        """
471
        Dictionarizes a certificate directly fetched from the database, but adds subject info.
472
        Contains full information.
473
        :param c: target cert
474
        :return: certificate dict (compliant with some parts of the REST API)
475
        """
476

    
477
        Logger.info(f"Function launched.")
478

    
479
        subj = self.certificate_service.get_subject_from_certificate(c)
480
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
481
        if c_issuer is None:
482
            return None
483

    
484
        return {
485
            SUBJECT: subj.to_dict(),
486
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
487
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
488
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
489
            CA: c_issuer.certificate_id
490
        }
491

    
492
    def get_private_key_of_a_certificate(self, id):
493
        """
494
        Get a private key used to sign a certificate in PEM format specified by certificate's ID
495

    
496
        :param id: ID of a certificate whose private key is to be queried
497
        :type id: dict | bytes
498

    
499
        :rtype: PemResponse
500
        """
501

    
502
        Logger.info(f"\n\t{request.referrer}"
503
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
504
                    f"\n\tCertificate ID = {id}")
505

    
506
        # try to parse the supplied ID
507
        try:
508
            v = int(id)
509
        except ValueError:
510
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
511
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
512

    
513
        # find a certificate using the given ID
514
        cert = self.certificate_service.get_certificate(v)
515

    
516
        if cert is None:
517
            Logger.error(f"No such certificate found 'ID = {v}'.")
518
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
519
        else:
520
            # certificate exists, fetch it's private key
521
            private_key = self.key_service.get_key(cert.private_key_id)
522
            if cert is None:
523
                Logger.error(f"Internal server error (certificate's private key cannot be found).")
524
                return E_NO_CERT_PRIVATE_KEY_FOUND, C_INTERNAL_SERVER_ERROR
525
            else:
526
                return {"success": True, "data": private_key.private_key}, C_SUCCESS
527

    
528
    def get_public_key_of_a_certificate(self, id):
529
        """
530
        Get a public key of a certificate in PEM format specified by certificate's ID
531

    
532
        :param id: ID of a certificate whose public key is to be queried
533
        :type id: dict | bytes
534

    
535
        :rtype: PemResponse
536
        """
537

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

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

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

    
552
        if cert is None:
553
            Logger.error(f"No such certificate found 'ID = {v}'.")
554
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
555
        else:
556
            return {"success": True, "data": self.certificate_service.get_public_key_from_certificate(cert)}, C_SUCCESS
557

    
558
    def delete_certificate(self, id):
559
        """
560
        Deletes a certificate identified by ID, including its corresponding subtree (all descendants).
561
        :param id: target certificate ID
562
        :rtype: DeleteResponse
563
        """
564

    
565
        Logger.info(f"\n\t{request.referrer}"
566
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
567
                    f"\n\tCertificate ID = {id}")
568

    
569
        try:
570
            v = int(id)
571
        except ValueError:
572
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
573
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
574

    
575
        try:
576
            self.certificate_service.delete_certificate(v)
577
        except CertificateNotFoundException:
578
            Logger.error(f"No such certificate found 'ID = {v}'.")
579
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
580
        except DatabaseException:
581
            Logger.error(f"Internal server error (corrupted database).")
582
            return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
583
        except CertificateStatusInvalidException or RevocationReasonInvalidException or UnknownException:
584
            Logger.error(f"Internal server error (unknown origin).")
585
            return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR
586

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