Projekt

Obecné

Profil

Stáhnout (6.01 KB) Statistiky
| Větev: | Tag: | Revize:
1
import os
2

    
3
from flask import Flask, redirect, request
4
from flask_injector import FlaskInjector
5
from injector import Injector
6
from werkzeug.exceptions import HTTPException
7

    
8
from src.config import configuration
9
from src.config.configuration import Configuration
10
from src.config.connection_provider import ConnectionProvider
11
from src.controllers.certificates_controller import CertController
12
from src.controllers.crl_ocsp_controller import CrlOcspController
13
from src.controllers.exception_handlers import handle_cryptography_exception, handle_database_exception, \
14
    handle_generic_exception
15
from src.exceptions.database_exception import DatabaseException
16
from src.services.cryptography import CryptographyService, CryptographyException
17
from src.utils.logger import Logger
18

    
19
app = Flask(__name__)
20

    
21

    
22
@app.route('/')
23
def index():
24
    return redirect("/static/index.html")
25

    
26

    
27
@app.route('/api/certificates', methods=["POST"])
28
def create_certificate(certificate_controller: CertController):
29
    return certificate_controller.create_certificate()
30

    
31

    
32
@app.route('/api/certificates', methods=["GET"])
33
def get_cert_list(certificate_controller: CertController):
34
    return certificate_controller.get_certificate_list()
35

    
36

    
37
@app.route('/api/certificates/<id>', methods=["GET"])
38
def get_cert(id, certificate_controller: CertController):
39
    return certificate_controller.get_certificate_by_id(id)
40

    
41

    
42
@app.route('/api/certificates/<id>', methods=["PATCH"])
43
def set_certificate_status(id, certificate_controller: CertController):
44
    return certificate_controller.set_certificate_status(id)
45

    
46

    
47
@app.route('/api/certificates/<id>', methods=["DELETE"])
48
def delete_certificate(id, certificate_controller: CertController):
49
    return certificate_controller.delete_certificate(id)
50

    
51

    
52
@app.route('/api/certificates/<id>/details', methods=["GET"])
53
def get_cert_details(id, certificate_controller: CertController):
54
    return certificate_controller.get_certificate_details_by_id(id)
55

    
56

    
57
@app.route('/api/certificates/<id>/root', methods=["GET"])
58
def get_cert_root(id, certificate_controller: CertController):
59
    return certificate_controller.get_certificate_root_by_id(id)
60

    
61

    
62
@app.route('/api/certificates/<id>/chain', methods=["GET"])
63
def get_cert_chain(id, certificate_controller: CertController):
64
    return certificate_controller.get_certificate_trust_chain_by_id(id)
65

    
66

    
67
@app.route('/api/certificates/<id>/privatekey', methods=["GET"])
68
def get_private_key_of_a_certificate(id, certificate_controller: CertController):
69
    return certificate_controller.get_private_key_of_a_certificate(id)
70

    
71

    
72
@app.route('/api/certificates/<id>/publickey', methods=["GET"])
73
def get_public_key_of_a_certificate(id, certificate_controller: CertController):
74
    return certificate_controller.get_public_key_of_a_certificate(id)
75

    
76

    
77
@app.route('/api/crl/<id>', methods=["GET"])
78
def get_crl_of_issuer(id, crl_ocsp_controller: CrlOcspController):
79
    return crl_ocsp_controller.get_crl(id)
80

    
81

    
82
@app.route('/api/ocsp/<id>/<path:ocsp_request>', methods=["GET"])
83
def get_ocsp_of_issuer_get(id, ocsp_request, crl_ocsp_controller: CrlOcspController):
84
    return crl_ocsp_controller.get_ocsp_from_base64(id, ocsp_request)
85

    
86

    
87
@app.route('/api/ocsp/<id>', methods=["POST"])
88
def get_ocsp_of_issuer_post(id, crl_ocsp_controller: CrlOcspController):
89
    return crl_ocsp_controller.get_ocsp_from_der(id, request.data)
90

    
91

    
92
@app.route('/api/certificates/<id>/identity', methods=["POST"])
93
def generate_certificate_pkcs_identity(id, certificate_controller: CertController):
94
    return certificate_controller.generate_certificate_pkcs_identity(id)
95

    
96

    
97
@app.errorhandler(CryptographyException)
98
def cryptography_error(e):
99
    return handle_cryptography_exception(e)
100

    
101

    
102
@app.errorhandler(DatabaseException)
103
def database_error(e):
104
    return handle_database_exception(e)
105

    
106

    
107
@app.errorhandler(Exception)
108
def generic_exception(e):
109
    if isinstance(e, HTTPException):
110
        # handle HTTPException exceptions here (MethodNotAllowed for example)
111
        Logger.warning(f""" HTTPException occurred: "{str(e)}" """)
112
        return str(e), e.code
113
    return handle_generic_exception(e)
114

    
115

    
116
def initialize_app(application) -> bool:
117
    """
118
    Initializes the application
119
        -   configure dependency injection
120
        -   check whether OpenSSL is on the system
121
    :param application Flask Application to be initialized.
122
    :return: boolean flag indicating whether initialization was successful or not
123
    """
124
    modules = [configuration.configure_env_variable, ConnectionProvider]
125
    injector = Injector(modules)
126
    FlaskInjector(app=application, modules=modules)
127

    
128
    config = injector.get(Configuration)
129
    configuration.configure_logging(config)
130

    
131
    Logger.info(f"Using configuration file: {config.config_file}")
132

    
133
    # There's a little dependency on the CryptoService, which is not a pretty thing from
134
    # architectural point of view. However it is only a minimal piece of code and
135
    # it makes sense to do it in this way instead of trying to run openssl via subprocess here
136
    cryptography_service = injector.get(CryptographyService)
137
    try:
138
        # if version string is returned, OpenSSL is present on the system
139
        Logger.info(f"Using {cryptography_service.get_openssl_version()}")
140
        return True
141
    except CryptographyException:
142
        # If getting the version string throws an exception the OpenSSL is not available
143
        print("OpenSSL was not located on the system. Application will now exit.")
144
        Logger.error(f"OpenSSL was not located on the system. Application will now exit.")
145
        return False
146

    
147

    
148
# app initialization must follow endpoint declaration (after all Flask decoration)
149
with app.app_context():
150
    if not initialize_app(app):
151
        print("Failed to initialize app, aborting...")
152
        Logger.error(f"Failed to initialize app, aborting...")
153
        exit(-1)
154

    
155
if __name__ == '__main__':
156
    app_host = "0.0.0.0"
157
    app_port = 5000
158

    
159
    # TODO better load this from config.py
160
    if "FLASK_HOST" in os.environ:
161
        app_host = os.environ["FLASK_HOST"]
162

    
163
    if "FLASK_PORT" in os.environ:
164
        app_host = os.environ["FLASK_PORT"]
165

    
166
    app.run(host=app_host, port=app_port)
(7-7/13)