diff --git a/src/fireedge/README.md b/src/fireedge/README.md index ae9ee94e36..b3e50e7817 100644 --- a/src/fireedge/README.md +++ b/src/fireedge/README.md @@ -26,7 +26,7 @@ Fire Edge server and client - Other: check file `src/config/command-params.js`. if requires it to be in a specific zone you must put it at the end but before the query /feredation=ZONE_ID (replace ZONE_ID for the zone id) - **zeroMQ** - Websocket connection call to: `ws://127.0.0.1:2616/?token=JWT` + Websocket connection call to: `ws://127.0.0.1:2616/zeromq/?token=JWT` ## Troubleshooting diff --git a/src/fireedge/fireedge-server.conf b/src/fireedge/fireedge-server.conf index 7f80a559f2..085b5a58f7 100644 --- a/src/fireedge/fireedge-server.conf +++ b/src/fireedge/fireedge-server.conf @@ -8,8 +8,8 @@ LOG: prod # Enable cors (cross-origin resource sharing) CORS: true -# JWT user password encryption key (AUTH) -TOKEN_SECRET: secret_token +# Fireedge server port +PORT: 2616 # OpenNebula Zones: use it if you have oned and fireedge on different servers # DEFAULT_ZONE: diff --git a/src/fireedge/src/server/index.js b/src/fireedge/src/server/index.js index 152cdd8ce6..cb54d6d3ca 100644 --- a/src/fireedge/src/server/index.js +++ b/src/fireedge/src/server/index.js @@ -1,57 +1,61 @@ -import path from 'path'; -import express from 'express'; -import webpack from 'webpack'; -import helmet from 'helmet'; -import morgan from 'morgan'; -import cors from 'cors'; -import compression from 'compression'; -import bodyParser from 'body-parser'; -import { env } from 'process'; +import path from 'path' +import express from 'express' +import webpack from 'webpack' +import helmet from 'helmet' +import morgan from 'morgan' +import cors from 'cors' +import compression from 'compression' +import bodyParser from 'body-parser' +import { env } from 'process' import { accessSync, constants, createWriteStream, readFileSync -} from 'fs-extra'; -import http from 'http'; -import https from 'https'; -import { defaultTypeLog, defaultPort } from './utils/constants/defaults'; +} from 'fs-extra' +import http from 'http' +import https from 'https' +import { defaultTypeLog, defaultPort, defaultWebpackMode } from './utils/constants/defaults' import { validateServerIsSecure, getCert, getKey, - genPathResources -} from './utils/server'; + genPathResources, + genFireedgeKey +} from './utils/server' import { entrypoint404, entrypointApi, entrypointApp -} from './routes/entrypoints'; -import { oneHooks } from './routes/websockets/zeromq'; -import { vmrcUpgrade } from './routes/websockets/vmrc'; -import { guacamole } from './routes/websockets/guacamole'; -import { messageTerminal, getConfig } from './utils'; +} from './routes/entrypoints' +import { oneHooks } from './routes/websockets/zeromq' +import { vmrcUpgrade } from './routes/websockets/vmrc' +import { guacamole } from './routes/websockets/guacamole' +import { messageTerminal, getConfig } from './utils' // set paths -genPathResources(); +genPathResources() + +// set fireedge_key +genFireedgeKey() // destructure imports -const unsecureServer = http.createServer; -const secureServer = https.createServer; +const unsecureServer = http.createServer +const secureServer = https.createServer -const app = express(); +const app = express() -let frontPath = 'client'; +let frontPath = 'client' // settings -const appConfig = getConfig(); -const port = appConfig.PORT || defaultPort; -const userLog = appConfig.LOG || 'dev'; +const appConfig = getConfig() +const port = appConfig.PORT || defaultPort +const userLog = appConfig.LOG || 'dev' -if (env.NODE_ENV === 'development') { +if (env.NODE_ENV === defaultWebpackMode) { // eslint-disable-next-line global-require - const config = require('../../webpack.config.dev.client'); - const compiler = webpack(config); + const config = require('../../webpack.config.dev.client') + const compiler = webpack(config) app.use( // eslint-disable-next-line global-require require('webpack-dev-middleware')(compiler, { @@ -67,64 +71,64 @@ if (env.NODE_ENV === 'development') { chunkModules: false } }) - ); + ) // eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line global-require - app.use(require('webpack-hot-middleware')(compiler)); - frontPath = '../client'; + app.use(require('webpack-hot-middleware')(compiler)) + frontPath = '../client' } -let log = morgan('dev'); +let log = morgan('dev') if (userLog === defaultTypeLog && global && global.FIREEDGE_LOG) { try { - accessSync(global.FIREEDGE_LOG, constants.W_OK); + accessSync(global.FIREEDGE_LOG, constants.W_OK) const logStream = createWriteStream(global.FIREEDGE_LOG, { flags: 'a' - }); - log = morgan('combined', { stream: logStream }); + }) + log = morgan('combined', { stream: logStream }) } catch (err) { const config = { color: 'red', message: 'Error: %s', type: err.message || '' - }; - messageTerminal(config); + } + messageTerminal(config) } } -app.use(helmet.hidePoweredBy()); -app.use(compression()); -app.use('/client', express.static(path.resolve(__dirname, frontPath))); +app.use(helmet.hidePoweredBy()) +app.use(compression()) +app.use('/client', express.static(path.resolve(__dirname, frontPath))) // log request -app.use(log); +app.use(log) // cors if (appConfig.CORS) { - app.use(cors()); + app.use(cors()) } // post params parser body -app.use(bodyParser.urlencoded({ extended: false })); -app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({ extended: false })) +app.use(bodyParser.json()) -app.use('/api', entrypointApi); // opennebula Api routes -app.get('/*', entrypointApp); +app.use('/api', entrypointApi) // opennebula Api routes +app.get('/*', entrypointApp) // 404 - public -app.get('*', entrypoint404); +app.get('*', entrypoint404) const appServer = validateServerIsSecure() ? secureServer( - { - key: readFileSync(getKey(), 'utf8'), - cert: readFileSync(getCert(), 'utf8') - }, - app - ) - : unsecureServer(app); + { + key: readFileSync(getKey(), 'utf8'), + cert: readFileSync(getCert(), 'utf8') + }, + app + ) + : unsecureServer(app) -oneHooks(appServer); +oneHooks(appServer) let config = { color: 'red', message: 'Server no start' -}; +} appServer.listen(port, '0.0.0.0', err => { if (!err) { @@ -132,9 +136,9 @@ appServer.listen(port, '0.0.0.0', err => { color: 'green', type: port, message: 'Server listen in port %s' - }; + } } - messageTerminal(config); -}); -vmrcUpgrade(appServer); -guacamole(appServer); + messageTerminal(config) +}) +vmrcUpgrade(appServer) +guacamole(appServer) diff --git a/src/fireedge/src/server/routes/api/auth/functions.js b/src/fireedge/src/server/routes/api/auth/functions.js index 29ca4955f6..1b69409995 100644 --- a/src/fireedge/src/server/routes/api/auth/functions.js +++ b/src/fireedge/src/server/routes/api/auth/functions.js @@ -203,12 +203,6 @@ const setZones = () => { } }; -const setOneConfig = () => { - if (global && global.oneConfig && global.oneConfig.length === 0) { - console.log('setConfig'); - } -}; - const userInfo = userData => { if (user && opennebulaToken && userData && userData.USER) { const informationUser = userData.USER; @@ -237,7 +231,6 @@ const userInfo = userData => { value, () => { setZones(); - setOneConfig(); // esto debe de estar antes de hacer el JWT }, next ); diff --git a/src/fireedge/src/server/routes/websockets/guacamole/options.js b/src/fireedge/src/server/routes/websockets/guacamole/options.js index 744a5647c4..821a87a3cd 100644 --- a/src/fireedge/src/server/routes/websockets/guacamole/options.js +++ b/src/fireedge/src/server/routes/websockets/guacamole/options.js @@ -1,7 +1,26 @@ +/* Copyright 2002-2019, OpenNebula Project, OpenNebula Systems */ +/* */ +/* Licensed under the Apache License, Version 2.0 (the "License"); you may */ +/* not use this file except in compliance with the License. You may obtain */ +/* a copy of the License at */ +/* */ +/* http://www.apache.org/licenses/LICENSE-2.0 */ +/* */ +/* Unless required by applicable law or agreed to in writing, software */ +/* distributed under the License is distributed on an "AS IS" BASIS, */ +/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ +/* See the License for the specific language governing permissions and */ +/* limitations under the License. */ +/* -------------------------------------------------------------------------- */ +const { genFireedgeKey } = require('server/utils/server') + +// set fireedge_key +genFireedgeKey() + const clientOptions = { crypt: { cypher: 'AES-256-CBC', - key: 'LSIOGCKYLSIOGCKYLSIOGCKYLSIOGCKY' + key: global.FIREEDGE_KEY || '' }, allowedUnencryptedConnectionSettings: { rdp: ['width', 'height', 'dpi'], @@ -10,18 +29,18 @@ const clientOptions = { telnet: ['color-scheme', 'font-name', 'font-size', 'width', 'height', 'dpi'] }, log: { verbose: false } -}; +} const callbacks = { processConnectionSettings: (settings, callback) => { if (settings.expiration && settings.expiration < Date.now()) { - return callback(new Error('Token expired')); + return callback(new Error('Token expired')) } - return callback(null, settings); + return callback(null, settings) } -}; +} module.exports = { clientOptions, callbacks -}; +} diff --git a/src/fireedge/src/server/utils/constants/defaults.js b/src/fireedge/src/server/utils/constants/defaults.js index 957f4ab7c7..a998c5c221 100644 --- a/src/fireedge/src/server/utils/constants/defaults.js +++ b/src/fireedge/src/server/utils/constants/defaults.js @@ -13,9 +13,9 @@ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ -const default2FAOpennebulaVar = 'TWO_FACTOR_AUTH_SECRET'; -const defaultIp = '127.0.0.1'; -const protocol = 'http'; +const default2FAOpennebulaVar = 'TWO_FACTOR_AUTH_SECRET' +const defaultIp = '127.0.0.1' +const protocol = 'http' const defaults = { httpMethod: { GET: 'GET', @@ -41,7 +41,7 @@ const defaults = { HOST: defaultIp, PORT: 2474 }, - defaultConfigFile: `fireedge-server.conf`, + defaultConfigFile: 'fireedge-server.conf', defaultTypeLog: 'prod', defaultWebpackMode: 'development', defaultWebpackDevTool: 'inline-source-map', @@ -49,7 +49,8 @@ const defaults = { defaultVarPath: '/var/lib/one', defaultEtcPath: '/etc/one', defaultLogFilename: 'fireedge.log', - defaultVmrcTokens: '/var/lib/one/sunstone_vnc_tokens/vmrc', + defaultKeyFilename: 'fireedge_key', + defaultVmrcTokens: 'sunstone_vnc_tokens/vmrc', defaultBaseURL: '', endpointVmrc: '/vmrc', defaultNamespace: 'one.', @@ -109,6 +110,6 @@ const defaults = { zh_CN: 'Chinese (China)', zh_TW: 'Chinese (Taiwan)' } -}; +} -module.exports = defaults; +module.exports = defaults diff --git a/src/fireedge/src/server/utils/jwt.js b/src/fireedge/src/server/utils/jwt.js index def14ccf61..2f8bcca66c 100644 --- a/src/fireedge/src/server/utils/jwt.js +++ b/src/fireedge/src/server/utils/jwt.js @@ -13,44 +13,38 @@ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ -const jwt = require('jwt-simple'); -const { DateTime } = require('luxon'); -const { messageTerminal } = require('./general'); -const { getConfig } = require('./yml'); - -// user config -const appConfig = getConfig(); - -const tokenSecret = appConfig.TOKEN_SECRET || null; +const jwt = require('jwt-simple') +const { DateTime } = require('luxon') +const { messageTerminal } = require('./general') const createToken = ( { id: iss, user: aud, token: jti }, iat = '', exp = '' ) => { - let rtn = null; - if (iss && aud && jti && iat && exp && tokenSecret) { + let rtn = null + if (iss && aud && jti && iat && exp && global && global.FIREEDGE_KEY) { const payload = { iss, aud, jti, iat, exp - }; - rtn = jwt.encode(payload, tokenSecret); + } + rtn = jwt.encode(payload, global.FIREEDGE_KEY) } - return rtn; -}; + return rtn +} const validateAuth = req => { - let rtn = false; + let rtn = false if (req && req.headers && req.headers.authorization) { - const authorization = req.headers.authorization; - const removeBearer = new RegExp('^Bearer ', 'i'); - const token = authorization.replace(removeBearer, ''); + const authorization = req.headers.authorization + const removeBearer = new RegExp('^Bearer ', 'i') + const token = authorization.replace(removeBearer, '') try { - const payload = jwt.decode(token, tokenSecret); - const now = DateTime.local(); + const payload = jwt.decode(token, global.FIREEDGE_KEY) + const now = DateTime.local() if ( payload && 'iss' in payload && @@ -60,29 +54,29 @@ const validateAuth = req => { 'exp' in payload && payload.exp >= now.toSeconds() ) { - const { iss, aud, jti, iat, exp } = payload; + const { iss, aud, jti, iat, exp } = payload rtn = { iss, aud, jti, iat, exp - }; + } } } catch (error) { const config = { color: 'red', type: 'ERROR', - error, + error: error.message || "", message: 'Error: %s' - }; - messageTerminal(config); + } + messageTerminal(config) } } - return rtn; -}; + return rtn +} module.exports = { createToken, validateAuth -}; +} diff --git a/src/fireedge/src/server/utils/server.js b/src/fireedge/src/server/utils/server.js index a6a213b0c0..799561b37c 100644 --- a/src/fireedge/src/server/utils/server.js +++ b/src/fireedge/src/server/utils/server.js @@ -12,65 +12,132 @@ /* See the License for the specific language governing permissions and */ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ -const { env } = require('process'); -const { Map } = require('immutable'); -const { existsSync } = require('fs-extra'); +const { env } = require('process') +const { Map } = require('immutable') +const { existsSync, readFileSync, createWriteStream } = require('fs-extra') -const { internalServerError } = require('./constants/http-codes'); +const { internalServerError } = require('./constants/http-codes') +const { messageTerminal } = require('server/utils/general') const { defaultLogFilename, defaultLogPath, - defaultVmrcTokens -} = require('./constants/defaults'); + defaultVmrcTokens, + defaultVarPath, + defaultKeyFilename, + defaultWebpackMode +} = require('./constants/defaults') -let cert = ''; -let key = ''; +let cert = '' +let key = '' const validateServerIsSecure = () => { - cert = `${__dirname}/../cert/cert.pem`; - key = `${__dirname}/../cert/key.pem`; - return existsSync && key && cert && existsSync(key) && existsSync(cert); -}; + const folder = '../cert/' + const path = process && process.env && process.env.NODE_ENV === defaultWebpackMode ? `${__dirname}/../../${folder}` : `${__dirname}/${folder}` + cert = `${path}cert.pem` + key = `${path}key.pem` + return existsSync && key && cert && existsSync(key) && existsSync(cert) +} -const getCert = () => cert; -const getKey = () => key; +const getCert = () => cert +const getKey = () => key const httpResponse = (response, data, message) => { - let rtn = Map(internalServerError).toObject(); - rtn.data = data; + let rtn = Map(internalServerError).toObject() + rtn.data = data if (response) { - rtn = Map(response).toObject(); + rtn = Map(response).toObject() } if (data || data === 0) { - rtn.data = data; + rtn.data = data } if (message) { - rtn.message = message; + rtn.message = message } - return rtn; -}; + return rtn +} + +const existsFile = (path = '', callback = () => undefined, error = () => undefined) => { + let rtn = false + try { + const file = readFileSync(path, 'utf8') + if (path && file) { + callback(file) + rtn = true + } + } catch (err) { + error(err) + } + return rtn +} + +const createFile = (path = '', data = '', callback = () => undefined, error = () => undefined) => { + let rtn = false + try { + const stream = createWriteStream(path) + stream.write(data) + callback(data, stream) + rtn = true + } catch (err) { + error(err) + } + return rtn +} + +const genFireedgeKey = () => { + if (global && !global.FIREEDGE_KEY) { + const { v4 } = require('uuid') + let uuidv4 = v4() + if (global.FIREEDGE_KEY_PATH) { + existsFile( + global.FIREEDGE_KEY_PATH, + filedata => { + if (filedata) { + uuidv4 = filedata + } + }, + () => { + createFile( + global.FIREEDGE_KEY_PATH, uuidv4, () => undefined, err => { + const config = { + color: 'red', + message: 'Error: %s', + type: err.message || '' + } + messageTerminal(config) + }) + } + ) + } + global.FIREEDGE_KEY = uuidv4 + } +} const genPathResources = () => { - const ONE_LOCATION = env && env.ONE_LOCATION; - const LOG_LOCATION = !ONE_LOCATION ? defaultLogPath : `${ONE_LOCATION}/var`; - const VMRC_LOCATION = !ONE_LOCATION - ? defaultVmrcTokens - : `${ONE_LOCATION}/${defaultVmrcTokens}`; + const ONE_LOCATION = env && env.ONE_LOCATION + const LOG_LOCATION = !ONE_LOCATION ? defaultLogPath : `${ONE_LOCATION}/var` + const VAR_LOCATION = !ONE_LOCATION ? defaultVarPath : `${ONE_LOCATION}/var` + const VMRC_LOCATION = !ONE_LOCATION ? defaultVarPath : ONE_LOCATION if (global) { if (!global.VMRC_TOKENS) { - global.VMRC_TOKENS = `${VMRC_LOCATION}/`; + global.VMRC_TOKENS = `${VMRC_LOCATION}/${defaultVmrcTokens}` } if (!global.FIREEDGE_LOG) { - global.FIREEDGE_LOG = `${LOG_LOCATION}/${defaultLogFilename}`; + global.FIREEDGE_LOG = `${LOG_LOCATION}/${defaultLogFilename}` + } + if (!global.FIREEDGE_KEY_PATH) { + global.FIREEDGE_KEY_PATH = `${VAR_LOCATION}/.one/${defaultKeyFilename}` } } -}; +} module.exports = { + existsFile, + createFile, httpResponse, validateServerIsSecure, genPathResources, + genFireedgeKey, getCert, getKey -}; +} diff --git a/src/fireedge/src/server/utils/yml.js b/src/fireedge/src/server/utils/yml.js index a303cc3111..b8e7dac52b 100644 --- a/src/fireedge/src/server/utils/yml.js +++ b/src/fireedge/src/server/utils/yml.js @@ -13,22 +13,25 @@ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ -const fs = require('fs-extra'); -const YAML = require('yaml'); -const { defaultConfigFile } = require('./constants/defaults'); +const { parse } = require('yaml'); +const { defaultConfigFile, defaultWebpackMode } = require('./constants/defaults'); +const { existsFile } = require('server/utils/server'); +const { messageTerminal } = require('server/utils/general'); const getConfig = () => { let rtn = {}; - if ( - defaultConfigFile && - fs && - fs.readFileSync && - fs.existsSync && - fs.existsSync(defaultConfigFile) - ) { - const file = fs.readFileSync(defaultConfigFile, 'utf8'); - rtn = YAML.parse(file); - } + const path = process && process.env && process.env.NODE_ENV === defaultWebpackMode ? `${__dirname}/../../../`: `${__dirname}/` + const file = existsFile(path+defaultConfigFile, filedata => { + rtn = parse(filedata); + }, err => { + const config = { + color: 'red', + message: 'Error: %s', + type: err.message || '' + } + messageTerminal(config) + }); + return rtn; }; diff --git a/src/fireedge/webpack.config.dev.client.js b/src/fireedge/webpack.config.dev.client.js index 8874a65000..4482fcd4e1 100644 --- a/src/fireedge/webpack.config.dev.client.js +++ b/src/fireedge/webpack.config.dev.client.js @@ -1,5 +1,6 @@ const path = require('path'); const webpack = require('webpack'); +const { defaultWebpackMode } = require('./src/server/utils/constants/defaults'); const js = { test: /\.js$/, @@ -8,7 +9,7 @@ const js = { }; module.exports = { - mode: 'development', + mode: defaultWebpackMode, entry: [ 'webpack-hot-middleware/client', path.resolve(__dirname, 'src', 'client', 'front-app.js') @@ -23,7 +24,7 @@ module.exports = { new webpack.HotModuleReplacementPlugin(), new webpack.DefinePlugin({ 'process.env': { - NODE_ENV: JSON.stringify('development') + NODE_ENV: JSON.stringify(defaultWebpackMode) } }) ],