Projekt

Obecné

Profil

Stáhnout (26.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
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_NOT_FOUND
215

    
216
        data = self.cert_to_dict_full(cert)
217
        if data is None:
218
            return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
219

    
220
        try:
221
            state = self.certificate_service.get_certificate_state(v)
222
            data["status"] = state
223
        except CertificateNotFoundException:
224
            Logger.error(f"No such certificate found 'ID = {id}'.")
225

    
226
        return {"success": True, "data": data}, C_SUCCESS
227

    
228
    def get_certificate_list(self):
229
        """get list of certificates
230

    
231
        Lists certificates based on provided filtering options
232

    
233
        :param filtering: Filter certificate type to be queried
234
        :type filtering: dict | bytes
235

    
236
        :rtype: CertificateListResponse
237
        """
238

    
239
        Logger.info(f"\n\t{request.referrer}"
240
                    f"\n\t{request.method}   {request.path}   {request.scheme}")
241

    
242
        targets = {ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID}                  # all targets
243
        issuer_id = -1
244

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

    
256
            Logger.info(f"\n\tRequest body:"
257
                        f"\n{dict_to_string(data)}")
258

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

    
284
                certs = [child for child in children if child.type_id in targets]
285

    
286
            elif len(targets) == TREE_NODE_TYPE_COUNT:                              # = 3 -> root node,
287
                                                                                    # intermediate node,
288
                                                                                    # or leaf node
289

    
290
                                                                                    # if filtering did not change the
291
                                                                                    # targets,
292
                certs = self.certificate_service.get_certificates()                 # fetch everything
293
            else:                                                                   # otherwise fetch targets only
294
                certs = list(chain(*(self.certificate_service.get_certificates(target) for target in targets)))
295
        else:
296
            certs = self.certificate_service.get_certificates()                     # if no params, fetch everything
297

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

    
317
    def get_certificate_root_by_id(self, id):
318
        """get certificate's root of trust chain by ID
319

    
320
        Get certificate's root of trust chain in PEM format by ID
321

    
322
        :param id: ID of a child certificate whose root is to be queried
323
        :type id: dict | bytes
324

    
325
        :rtype: PemResponse
326
        """
327

    
328
        Logger.info(f"\n\t{request.referrer}"
329
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
330
                    f"\n\tCertificate ID = {id}")
331

    
332
        try:
333
            v = int(id)
334
        except ValueError:
335
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
336
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
337

    
338
        cert = self.certificate_service.get_certificate(v)
339

    
340
        if cert is None:
341
            Logger.error(f"No such certificate found 'ID = {v}'.")
342
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
343

    
344
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
345
        if trust_chain is None or len(trust_chain) == 0:
346
            Logger.error(f"No such certificate found (empty list).")
347
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
348

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

    
351
    def get_certificate_trust_chain_by_id(self, id):
352
        """get certificate's trust chain by ID (including root certificate)
353

    
354
        Get certificate trust chain in PEM format by ID
355

    
356
        :param id: ID of a child certificate whose chain is to be queried
357
        :type id: dict | bytes
358

    
359
        :rtype: PemResponse
360
        """
361

    
362
        Logger.info(f"\n\t{request.referrer}"
363
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
364
                    f"\n\tCertificate ID = {id}")
365

    
366
        try:
367
            v = int(id)
368
        except ValueError:
369
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
370
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
371

    
372
        cert = self.certificate_service.get_certificate(v)
373

    
374
        if cert is None:
375
            Logger.error(f"No such certificate found 'ID = {v}'.")
376
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
377

    
378
        if cert.parent_id is None:
379
            Logger.error(f"Parent ID is empty in certificate 'ID = {v}'.")
380
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
381

    
382
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
383

    
384
        ret = []
385
        for intermediate in trust_chain:
386
            ret.append(intermediate.pem_data)
387

    
388
        return {"success": True, "data": "".join(ret)}, C_SUCCESS
389

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

    
399
        :rtype: SuccessResponse | ErrorResponse (see OpenAPI definition)
400
        """
401

    
402
        Logger.info(f"\n\t{request.referrer}"
403
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
404
                    f"\n\tCertificate ID = {id}")
405

    
406
        required_keys = {STATUS}  # required keys
407

    
408
        # check if the request contains a JSON body
409
        if request.is_json:
410
            request_body = request.get_json()
411

    
412
            Logger.info(f"\n\tRequest body:"
413
                        f"\n{dict_to_string(request_body)}")
414

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

    
422
            # verify that all required keys are present
423
            if not all(k in request_body for k in required_keys):
424
                Logger.error(f"Invalid request, missing parameters.")
425
                return E_MISSING_PARAMETERS, C_BAD_REQUEST
426

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

    
450
    def cert_to_dict_partial(self, c):
451
        """
452
        Dictionarizes a certificate directly fetched from the database. Contains partial information.
453
        :param c: target cert
454
        :return: certificate dict (compliant with some parts of the REST API)
455
        """
456

    
457
        # TODO check log
458
        Logger.debug(f"Function launched.")
459

    
460
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
461
        if c_issuer is None:
462
            return None
463

    
464
        return {
465
            ID: c.certificate_id,
466
            COMMON_NAME: c.common_name,
467
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
468
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
469
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
470
            ISSUER: {
471
                ID: c_issuer.certificate_id,
472
                COMMON_NAME: c_issuer.common_name
473
            }
474
        }
475

    
476
    def cert_to_dict_full(self, c):
477
        """
478
        Dictionarizes a certificate directly fetched from the database, but adds subject info.
479
        Contains full information.
480
        :param c: target cert
481
        :return: certificate dict (compliant with some parts of the REST API)
482
        """
483

    
484
        Logger.info(f"Function launched.")
485

    
486
        subj = self.certificate_service.get_subject_from_certificate(c)
487
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
488
        if c_issuer is None:
489
            return None
490

    
491
        return {
492
            SUBJECT: subj.to_dict(),
493
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
494
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
495
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
496
            CA: c_issuer.certificate_id
497
        }
498

    
499
    def get_private_key_of_a_certificate(self, id):
500
        """
501
        Get a private key used to sign a certificate in PEM format specified by certificate's ID
502

    
503
        :param id: ID of a certificate whose private key is to be queried
504
        :type id: dict | bytes
505

    
506
        :rtype: PemResponse
507
        """
508

    
509
        Logger.info(f"\n\t{request.referrer}"
510
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
511
                    f"\n\tCertificate ID = {id}")
512

    
513
        # try to parse the supplied ID
514
        try:
515
            v = int(id)
516
        except ValueError:
517
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
518
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
519

    
520
        # find a certificate using the given ID
521
        cert = self.certificate_service.get_certificate(v)
522

    
523
        if cert is None:
524
            Logger.error(f"No such certificate found 'ID = {v}'.")
525
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
526
        else:
527
            # certificate exists, fetch it's private key
528
            private_key = self.key_service.get_key(cert.private_key_id)
529
            if cert is None:
530
                Logger.error(f"Internal server error (certificate's private key cannot be found).")
531
                return E_NO_CERT_PRIVATE_KEY_FOUND, C_INTERNAL_SERVER_ERROR
532
            else:
533
                return {"success": True, "data": private_key.private_key}, C_SUCCESS
534

    
535
    def get_public_key_of_a_certificate(self, id):
536
        """
537
        Get a public key of a certificate in PEM format specified by certificate's ID
538

    
539
        :param id: ID of a certificate whose public key is to be queried
540
        :type id: dict | bytes
541

    
542
        :rtype: PemResponse
543
        """
544

    
545
        Logger.info(f"\n\t{request.referrer}"
546
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
547
                    f"\n\tCertificate ID = {id}")
548

    
549
        # try to parse the supplied ID
550
        try:
551
            v = int(id)
552
        except ValueError:
553
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
554
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
555

    
556
        # find a certificate using the given ID
557
        cert = self.certificate_service.get_certificate(v)
558

    
559
        if cert is None:
560
            Logger.error(f"No such certificate found 'ID = {v}'.")
561
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
562
        else:
563
            return {"success": True, "data": self.certificate_service.get_public_key_from_certificate(cert)}, C_SUCCESS
564

    
565
    def delete_certificate(self, id):
566
        """
567
        Deletes a certificate identified by ID, including its corresponding subtree (all descendants).
568
        :param id: target certificate ID
569
        :rtype: DeleteResponse
570
        """
571

    
572
        Logger.info(f"\n\t{request.referrer}"
573
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
574
                    f"\n\tCertificate ID = {id}")
575

    
576
        try:
577
            v = int(id)
578
        except ValueError:
579
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
580
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
581

    
582
        try:
583
            self.certificate_service.delete_certificate(v)
584
        except CertificateNotFoundException:
585
            Logger.error(f"No such certificate found 'ID = {v}'.")
586
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
587
        except DatabaseException:
588
            Logger.error(f"Internal server error (corrupted database).")
589
            return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
590
        except CertificateStatusInvalidException or RevocationReasonInvalidException or UnknownException:
591
            Logger.error(f"Internal server error (unknown origin).")
592
            return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR
593

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