21621: Add copy button to virtual code snippet for io panel json tab
[arvados.git] / services / workbench2 / config / getHttpsConfig.js
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 'use strict';
6
7 const fs = require('fs');
8 const path = require('path');
9 const crypto = require('crypto');
10 const chalk = require('react-dev-utils/chalk');
11 const paths = require('./paths');
12
13 // Ensure the certificate and key provided are valid and if not
14 // throw an easy to debug error
15 function validateKeyAndCerts({ cert, key, keyFile, crtFile }) {
16   let encrypted;
17   try {
18     // publicEncrypt will throw an error with an invalid cert
19     encrypted = crypto.publicEncrypt(cert, Buffer.from('test'));
20   } catch (err) {
21     throw new Error(
22       `The certificate "${chalk.yellow(crtFile)}" is invalid.\n${err.message}`
23     );
24   }
25
26   try {
27     // privateDecrypt will throw an error with an invalid key
28     crypto.privateDecrypt(key, encrypted);
29   } catch (err) {
30     throw new Error(
31       `The certificate key "${chalk.yellow(keyFile)}" is invalid.\n${
32         err.message
33       }`
34     );
35   }
36 }
37
38 // Read file and throw an error if it doesn't exist
39 function readEnvFile(file, type) {
40   if (!fs.existsSync(file)) {
41     throw new Error(
42       `You specified ${chalk.cyan(
43         type
44       )} in your env, but the file "${chalk.yellow(file)}" can't be found.`
45     );
46   }
47   return fs.readFileSync(file);
48 }
49
50 // Get the https config
51 // Return cert files if provided in env, otherwise just true or false
52 function getHttpsConfig() {
53   const { SSL_CRT_FILE, SSL_KEY_FILE, HTTPS } = process.env;
54   const isHttps = HTTPS === 'true';
55
56   if (isHttps && SSL_CRT_FILE && SSL_KEY_FILE) {
57     const crtFile = path.resolve(paths.appPath, SSL_CRT_FILE);
58     const keyFile = path.resolve(paths.appPath, SSL_KEY_FILE);
59     const config = {
60       cert: readEnvFile(crtFile, 'SSL_CRT_FILE'),
61       key: readEnvFile(keyFile, 'SSL_KEY_FILE'),
62     };
63
64     validateKeyAndCerts({ ...config, keyFile, crtFile });
65     return config;
66   }
67   return isHttps;
68 }
69
70 module.exports = getHttpsConfig;