Projekt

Obecné

Profil

Stáhnout (26.9 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
EXTENSIONS = "extensions"
26

    
27
TREE_NODE_TYPE_COUNT = 3
28

    
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

    
56

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

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

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

    
69
        Create a new certificate based on given information
70

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

    
74
        :rtype: CreatedResponse
75
        """
76

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

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

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

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

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

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

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

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

    
102
            usages_dict = {}
103

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

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

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

    
116
            extensions = ""
117
            if EXTENSIONS in body:
118
                extensions = body[EXTENSIONS]
119

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

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

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

    
139
                    if issuer_key is None:                                          # if it does not
140
                        Logger.error(f"Internal server error (corrupted database).")
141
                        self.key_service.delete_key(key.private_key_id)             # free
142
                        return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR        # and throw
143

    
144
                    f = self.certificate_service.create_ca if CA_ID in usages_dict and usages_dict[CA_ID] else \
145
                        self.certificate_service.create_end_cert
146

    
147
                    # noinspection PyArgumentList
148
                    cert = f(                                                       # create inter CA or end cert
149
                        key,                                                        # according to whether 'CA' is among
150
                        subject,                                                    # the usages' fields
151
                        issuer,
152
                        issuer_key,
153
                        usages=usages_dict,
154
                        days=body[VALIDITY_DAYS],
155
                        extensions=extensions
156
                    )
157
            except CryptographyException as e:
158
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
159

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

    
174
    def get_certificate_by_id(self, id):
175
        """get certificate by ID
176

    
177
        Get certificate in PEM format by ID
178

    
179
        :param id: ID of a certificate to be queried
180
        :type id: dict | bytes
181

    
182
        :rtype: PemResponse
183
        """
184

    
185
        Logger.info(f"\n\t{request.referrer}"
186
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
187
                    f"\n\tCertificate ID = {id}")
188
        try:
189
            v = int(id)
190
        except ValueError:
191
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
192
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
193

    
194
        cert = self.certificate_service.get_certificate(v)
195

    
196
        if cert is None:
197
            Logger.error(f"No such certificate found 'ID = {v}'.")
198
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
199
        else:
200
            return {"success": True, "data": cert.pem_data}, C_SUCCESS
201

    
202
    def get_certificate_details_by_id(self, id):
203
        """get certificate's details by ID
204

    
205
        Get certificate details by ID
206

    
207
        :param id: ID of a certificate whose details are to be queried
208
        :type id: dict | bytes
209

    
210
        :rtype: CertificateResponse
211
        """
212

    
213
        Logger.info(f"\n\t{request.referrer}"
214
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
215
                    f"\n\tCertificate ID = {id}")
216

    
217
        try:
218
            v = int(id)
219
        except ValueError:
220
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
221
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
222

    
223
        cert = self.certificate_service.get_certificate(v)
224

    
225
        if cert is None:
226
            Logger.error(f"No such certificate found 'ID = {v}'.")
227
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
228

    
229
        data = self.cert_to_dict_full(cert)
230
        if data is None:
231
            return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
232

    
233
        try:
234
            state = self.certificate_service.get_certificate_state(v)
235
            data["status"] = state
236
        except CertificateNotFoundException:
237
            Logger.error(f"No such certificate found 'ID = {id}'.")
238

    
239
        return {"success": True, "data": data}, C_SUCCESS
240

    
241
    def get_certificate_list(self):
242
        """get list of certificates
243

    
244
        Lists certificates based on provided filtering options
245

    
246
        :param filtering: Filter certificate type to be queried
247
        :type filtering: dict | bytes
248

    
249
        :rtype: CertificateListResponse
250
        """
251

    
252
        Logger.info(f"\n\t{request.referrer}"
253
                    f"\n\t{request.method}   {request.path}   {request.scheme}")
254

    
255
        targets = {ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID}                  # all targets
256
        issuer_id = -1
257

    
258
        # the filtering parameter can be read as URL argument or as a request body
259
        if request.is_json or FILTERING in request.args.keys():                     # if the request carries JSON data
260
            if request.is_json:
261
                data = request.get_json()                                           # get it
262
            else:
263
                try:
264
                    data = {FILTERING: json.loads(request.args[FILTERING])}
265
                except JSONDecodeError:
266
                    Logger.error(f"The request must be JSON-formatted.")
267
                    return E_NOT_JSON_FORMAT, C_BAD_REQUEST
268

    
269
            Logger.info(f"\n\tRequest body:"
270
                        f"\n{dict_to_string(data)}")
271

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

    
297
                certs = [child for child in children if child.type_id in targets]
298

    
299
            elif len(targets) == TREE_NODE_TYPE_COUNT:                              # = 3 -> root node,
300
                                                                                    # intermediate node,
301
                                                                                    # or leaf node
302

    
303
                                                                                    # if filtering did not change the
304
                                                                                    # targets,
305
                certs = self.certificate_service.get_certificates()                 # fetch everything
306
            else:                                                                   # otherwise fetch targets only
307
                certs = list(chain(*(self.certificate_service.get_certificates(target) for target in targets)))
308
        else:
309
            certs = self.certificate_service.get_certificates()                     # if no params, fetch everything
310

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

    
330
    def get_certificate_root_by_id(self, id):
331
        """get certificate's root of trust chain by ID
332

    
333
        Get certificate's root of trust chain in PEM format by ID
334

    
335
        :param id: ID of a child certificate whose root is to be queried
336
        :type id: dict | bytes
337

    
338
        :rtype: PemResponse
339
        """
340

    
341
        Logger.info(f"\n\t{request.referrer}"
342
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
343
                    f"\n\tCertificate ID = {id}")
344

    
345
        try:
346
            v = int(id)
347
        except ValueError:
348
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
349
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
350

    
351
        cert = self.certificate_service.get_certificate(v)
352

    
353
        if cert is None:
354
            Logger.error(f"No such certificate found 'ID = {v}'.")
355
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
356

    
357
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
358
        if trust_chain is None or len(trust_chain) == 0:
359
            Logger.error(f"No such certificate found (empty list).")
360
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
361

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

    
364
    def get_certificate_trust_chain_by_id(self, id):
365
        """get certificate's trust chain by ID (including root certificate)
366

    
367
        Get certificate trust chain in PEM format by ID
368

    
369
        :param id: ID of a child certificate whose chain is to be queried
370
        :type id: dict | bytes
371

    
372
        :rtype: PemResponse
373
        """
374

    
375
        Logger.info(f"\n\t{request.referrer}"
376
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
377
                    f"\n\tCertificate ID = {id}")
378

    
379
        try:
380
            v = int(id)
381
        except ValueError:
382
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
383
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
384

    
385
        cert = self.certificate_service.get_certificate(v)
386

    
387
        if cert is None:
388
            Logger.error(f"No such certificate found 'ID = {v}'.")
389
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
390

    
391
        if cert.parent_id is None:
392
            Logger.error(f"Parent ID is empty in certificate 'ID = {v}'.")
393
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
394

    
395
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
396

    
397
        ret = []
398
        for intermediate in trust_chain:
399
            ret.append(intermediate.pem_data)
400

    
401
        return {"success": True, "data": "".join(ret)}, C_SUCCESS
402

    
403
    def set_certificate_status(self, id):
404
        """
405
        Revoke a certificate given by ID
406
            - revocation request may contain revocation reason
407
            - revocation reason is verified based on the possible predefined values
408
            - if revocation reason is not specified 'undefined' value is used
409
        :param id: Identifier of the certificate to be revoked
410
        :type id: int
411

    
412
        :rtype: SuccessResponse | ErrorResponse (see OpenAPI definition)
413
        """
414

    
415
        Logger.info(f"\n\t{request.referrer}"
416
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
417
                    f"\n\tCertificate ID = {id}")
418

    
419
        required_keys = {STATUS}  # required keys
420

    
421
        # check if the request contains a JSON body
422
        if request.is_json:
423
            request_body = request.get_json()
424

    
425
            Logger.info(f"\n\tRequest body:"
426
                        f"\n{dict_to_string(request_body)}")
427

    
428
            # try to parse certificate identifier -> if it is not int return error 400
429
            try:
430
                identifier = int(id)
431
            except ValueError:
432
                Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
433
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
434

    
435
            # verify that all required keys are present
436
            if not all(k in request_body for k in required_keys):
437
                Logger.error(f"Invalid request, missing parameters.")
438
                return E_MISSING_PARAMETERS, C_BAD_REQUEST
439

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

    
465
    def cert_to_dict_partial(self, c):
466
        """
467
        Dictionarizes a certificate directly fetched from the database. Contains partial information.
468
        :param c: target cert
469
        :return: certificate dict (compliant with some parts of the REST API)
470
        """
471

    
472
        # TODO check log
473
        Logger.debug(f"Function launched.")
474

    
475
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
476
        if c_issuer is None:
477
            return None
478

    
479
        return {
480
            ID: c.certificate_id,
481
            COMMON_NAME: c.common_name,
482
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
483
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
484
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
485
            ISSUER: {
486
                ID: c_issuer.certificate_id,
487
                COMMON_NAME: c_issuer.common_name
488
            }
489
        }
490

    
491
    def cert_to_dict_full(self, c):
492
        """
493
        Dictionarizes a certificate directly fetched from the database, but adds subject info.
494
        Contains full information.
495
        :param c: target cert
496
        :return: certificate dict (compliant with some parts of the REST API)
497
        """
498

    
499
        Logger.info(f"Function launched.")
500

    
501
        subj = self.certificate_service.get_subject_from_certificate(c)
502
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
503
        if c_issuer is None:
504
            return None
505

    
506
        return {
507
            SUBJECT: subj.to_dict(),
508
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
509
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
510
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
511
            CA: c_issuer.certificate_id
512
        }
513

    
514
    def get_private_key_of_a_certificate(self, id):
515
        """
516
        Get a private key used to sign a certificate in PEM format specified by certificate's ID
517

    
518
        :param id: ID of a certificate whose private key is to be queried
519
        :type id: dict | bytes
520

    
521
        :rtype: PemResponse
522
        """
523

    
524
        Logger.info(f"\n\t{request.referrer}"
525
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
526
                    f"\n\tCertificate ID = {id}")
527

    
528
        # try to parse the supplied ID
529
        try:
530
            v = int(id)
531
        except ValueError:
532
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
533
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
534

    
535
        # find a certificate using the given ID
536
        cert = self.certificate_service.get_certificate(v)
537

    
538
        if cert is None:
539
            Logger.error(f"No such certificate found 'ID = {v}'.")
540
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
541
        else:
542
            # certificate exists, fetch it's private key
543
            private_key = self.key_service.get_key(cert.private_key_id)
544
            if cert is None:
545
                Logger.error(f"Internal server error (certificate's private key cannot be found).")
546
                return E_NO_CERT_PRIVATE_KEY_FOUND, C_INTERNAL_SERVER_ERROR
547
            else:
548
                return {"success": True, "data": private_key.private_key}, C_SUCCESS
549

    
550
    def get_public_key_of_a_certificate(self, id):
551
        """
552
        Get a public key of a certificate in PEM format specified by certificate's ID
553

    
554
        :param id: ID of a certificate whose public key is to be queried
555
        :type id: dict | bytes
556

    
557
        :rtype: PemResponse
558
        """
559

    
560
        Logger.info(f"\n\t{request.referrer}"
561
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
562
                    f"\n\tCertificate ID = {id}")
563

    
564
        # try to parse the supplied ID
565
        try:
566
            v = int(id)
567
        except ValueError:
568
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
569
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
570

    
571
        # find a certificate using the given ID
572
        cert = self.certificate_service.get_certificate(v)
573

    
574
        if cert is None:
575
            Logger.error(f"No such certificate found 'ID = {v}'.")
576
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
577
        else:
578
            return {"success": True, "data": self.certificate_service.get_public_key_from_certificate(cert)}, C_SUCCESS
579

    
580
    def delete_certificate(self, id):
581
        """
582
        Deletes a certificate identified by ID, including its corresponding subtree (all descendants).
583
        :param id: target certificate ID
584
        :rtype: DeleteResponse
585
        """
586

    
587
        Logger.info(f"\n\t{request.referrer}"
588
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
589
                    f"\n\tCertificate ID = {id}")
590

    
591
        try:
592
            v = int(id)
593
        except ValueError:
594
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
595
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
596

    
597
        try:
598
            self.certificate_service.delete_certificate(v)
599
        except CertificateNotFoundException:
600
            Logger.error(f"No such certificate found 'ID = {v}'.")
601
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
602
        except DatabaseException:
603
            Logger.error(f"Internal server error (corrupted database).")
604
            return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
605
        except CertificateStatusInvalidException or RevocationReasonInvalidException or UnknownException:
606
            Logger.error(f"Internal server error (unknown origin).")
607
            return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR
608

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