Commit 44832bc4 authored by guillecxb's avatar guillecxb
Browse files

add backend env variables

parent 9828322f
Loading
Loading
Loading
Loading
+66 −57
Original line number Diff line number Diff line
@@ -19,10 +19,7 @@ app = Flask(__name__)
# Configurar CORS para todas las rutas
CORS(app, resources={r"/api/*": {"origins": "http://localhost:3001"}})

#CORS(app) # habilita CORS para todas las rutas en la aplicación

# Register blueprints (routes)
# other option modify URL ->  app.register_blueprint(backoffice_routes, url_prefix="/resources")
app.register_blueprint(backoffice_routes, url_prefix="/api")
app.register_blueprint(access_routes, url_prefix="/api")
app.register_blueprint(invokers_routes, url_prefix="/api/invokers")
@@ -30,18 +27,10 @@ app.register_blueprint(providers_routes, url_prefix="/api/providers")
app.register_blueprint(apis_routes, url_prefix="/api/apis")
app.register_blueprint(users_routes, url_prefix="/api/users")


@app.route("/api/options", methods=["OPTIONS"])
def handle_options():
    return "", 200


# @app.route('/', defaults={'path': ''})
# @app.route('/<path:path>', methods=['OPTIONS'])
# def handle_options(path):     
#     return 'Success', 200


# Configure JWT
app.config["JWT_SECRET_KEY"] = "super-secret"
jwt = JWTManager(app)
@@ -68,11 +57,19 @@ csr_request = dump_certificate_request(FILETYPE_PEM, req)
# Get private key
private_key = dump_privatekey(FILETYPE_PEM, key)

# Leer variable de entorno para determinar si se carga desde Vault o desde variables de entorno
LOAD_FROM_VAULT = os.getenv('LOAD_FROM_VAULT', 'true').lower() == 'true'

# Ensure the certs directory exists
os.makedirs('newcerts', exist_ok=True)

if LOAD_FROM_VAULT:
    # Cargar certificados desde Vault
    print(f"Using Vault token: {os.getenv('VAULT_TOKEN')}")

# Get ca.cert from vault
    # Get ca.cert from Vault
    config = Config().get_config()  # get configuration from config.py
url = 'http://{}:{}/v1/secret/data/ca'.format(os.getenv('VAULT_HOSTNAME'), os.getenv('VAULT_PORT'))   # http://vault:8200/v1/secret/data/ca
    url = 'http://{}:{}/v1/secret/data/ca'.format(os.getenv('VAULT_HOSTNAME'), os.getenv('VAULT_PORT'))  
    headers = {'X-Vault-Token': os.getenv('VAULT_TOKEN')}
    response = requests.request("GET", url, headers=headers, verify=False)

@@ -82,14 +79,13 @@ print(response)

    ca_cert = json.loads(response.text)["data"]["data"]["ca"]

# print ("CA CERT URL: ", url)
# print ("VAULT_HOSTNAME", os.get_environ('VAULT_HOSTNAME'))
# print ("VAULT_PORT", os.get_environ('VAULT_PORT'))

# Request Vault a CA certificate to backoffice application
url = 'http://{}:{}/v1/pki_int/sign/my-ca'.format(os.getenv('VAULT_HOSTNAME'), os.getenv('VAULT_PORT'))  # http://vault:8200/v1/pki_int/sign/my-ca
    # Save ca_cert
    ca_file = open('newcerts/ca_root.crt', 'wb+')
    ca_file.write(bytes(ca_cert, 'utf-8'))
    ca_file.close()

headers = {'X-Vault-Token': os.getenv('VAULT_TOKEN')}  # token = dev-only-token -> for dev environment
    # Request Vault to sign the CSR
    url = 'http://{}:{}/v1/pki_int/sign/my-ca'.format(os.getenv('VAULT_HOSTNAME'), os.getenv('VAULT_PORT'))  
    data = {
        'format': 'pem_bundle',
        'ttl': '43000h',
@@ -99,15 +95,6 @@ data = {
    response = requests.request("POST", url, headers=headers, data=data, verify=False)
    backoffice_cert = json.loads(response.text)['data']['certificate']


# Ensure the certs directory exists
os.makedirs('newcerts', exist_ok=True)

# Save ca_cert
ca_file = open('newcerts/ca_root.crt', 'wb+')
ca_file.write(bytes(ca_cert, 'utf-8'))
ca_file.close()

    # Save private_key
    private_key_file = open("newcerts/superadmin.key", 'wb+')
    private_key_file.write(private_key)
@@ -118,10 +105,32 @@ certification_file = open('newcerts/superadmin.crt', 'wb+')
    certification_file.write(bytes(backoffice_cert, 'utf-8'))
    certification_file.close()

else:
    # Cargar certificados desde variables de entorno
    ca_cert = os.getenv('CA_CERT')
    private_key_content = os.getenv('PRIVATE_KEY')
    backoffice_cert_content = os.getenv('BACKOFFICE_CERT')

    if not ca_cert or not private_key_content or not backoffice_cert_content:
        print("Error: Las variables de entorno CA_CERT, PRIVATE_KEY y BACKOFFICE_CERT deben estar definidas")
        exit(1)

    # Guardar el certificado CA
    with open('newcerts/ca_root.crt', 'wb+') as ca_file:
        ca_file.write(bytes(ca_cert, 'utf-8'))

    # Guardar la clave privada
    with open('newcerts/superadmin.key', 'wb+') as private_key_file:
        private_key_file.write(bytes(private_key_content, 'utf-8'))

    # Guardar el certificado de backoffice
    with open('newcerts/superadmin.crt', 'wb+') as certification_file:
        certification_file.write(bytes(backoffice_cert_content, 'utf-8'))

#----------------------------------------
# launch
#----------------------------------------

# the applicacions starts here in every interface and port 8080
# The application starts here, on every interface and port 8080
if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=8080)
+4 −0
Original line number Diff line number Diff line
@@ -21,6 +21,10 @@ services:
      - VAULT_PORT=8200
      - VAULT_TOKEN=hvs.V4qI3b2X0V5g2YRcS4TF4uGs  # token que había en VAULT
      # - VAULT_TOKEN=dev-only-token
      - LOAD_FROM_VAULT=true
      - CA_CERT=-----BEGIN CERTIFICATE-----\nMIIDdzCCAl+gAwIBAgIJAJ8pZw+jMA0GCSqGSIb3DQEBCwUAMFwxCzAJBgNVBAYT\n-----END CERTIFICATE-----
      - PRIVATE_KEY=-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAM2DD45Ol\n-----END CERTIFICATE-----
      - BACKOFFICE_CERT=-----BEGIN CERTIFICATE-----\nMIIDXTCCAkWgAwIBAgIJAJ8pZw+jMA0GCSqGSIb3DQEBCwUAMFwxCzAJ\n-----END CERTIFICATE-----
    restart: unless-stopped
    
networks: