All files / lib/agent settings.js

100% Statements 121/121
98.76% Branches 80/81
100% Functions 23/23
100% Lines 120/120

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490    43x 43x                   12x   12x 3x 9x 3x     12x                     12x   12x 3x 9x       3x     12x                 12x   12x       2x 2x       1x     11x                       12x           12x                                         6x 1x     6x 2x           6x 3x     6x 1x                         8x 1x     7x 6x   6x                     14x           14x 5x 9x 8x                   1x     11x         11x             11x           11x     43x                     43x         14x         14x 1x     13x 3x 1x 1x 2x 1x         1x       13x                     43x       14x   14x 1x 13x 2x 2x   1x       14x                     43x           15x 1x     14x 2x 2x 12x 2x 2x   1x   2x 2x     14x                   43x 17x   17x 3x   1x 14x 3x 3x 1x   2x       17x     43x                                                                                                                       43x         25x 125x               100x 142x                         43x               13x 2x 1x   1x 2x   1x 1x         13x                         43x           15x           15x             15x 1x 14x 3x 9x   8x     8x           3x 1x       14x     43x  
"use strict";
 
const _ = require("lodash");
const url = require("./url");
 
/**
 * Gets username from url of from parameters settings
 *
 * @param {String} urlUsername - string which could contains username
 *
 * @returns {Object} settings username snippet
 */
function parseConnectionStringUsername(urlUsername) {
  var usernameSnippet = {};
 
  if (_.isString(urlUsername) && urlUsername) {
    usernameSnippet.username = urlUsername;
  } else if (_.isString(process.env.ODATA_USER) && process.env.ODATA_USER) {
    usernameSnippet.username = process.env.ODATA_USER;
  }
 
  return usernameSnippet;
}
 
/**
 * Gets username from url of from parameters settings
 *
 * @param {String} urlPassword - string which could contains password in url
 *
 * @returns {Object} settings password snippet
 */
function parseConnectionStringPassword(urlPassword) {
  var passwordSnippet = {};
 
  if (_.isString(urlPassword) && urlPassword) {
    passwordSnippet.password = urlPassword;
  } else if (
    _.isString(process.env.ODATA_PASSWORD) &&
    process.env.ODATA_PASSWORD
  ) {
    passwordSnippet.password = process.env.ODATA_PASSWORD;
  }
 
  return passwordSnippet;
}
 
/**
 * Try to get metadata parameters from environment variable
 *
 * @returns {Object} settings parameters snippet
 */
function parseConnectionParameters() {
  var metadataParametersSnippet = {};
 
  if (
    _.isString(process.env.ODATA_PARAMETERS) &&
    process.env.ODATA_PARAMETERS
  ) {
    try {
      metadataParametersSnippet.parameters = JSON.parse(
        process.env.ODATA_PARAMETERS
      );
    } catch (err) {
      throw Error("ODATA_PARAMETERS variable is not valid JSON.");
    }
  }
  return metadataParametersSnippet;
}
 
/**
 * Try to get metadata parameters from environment variable
 *
 * @param {String} connectionUrl - string which could contains corrently defined url
 * @param {Object} parameters - reference to parameter structure which is updated by method
 *
 * @return {Object} returns structure defining OData endpoint
 */
function parseConnectionString(connectionUrl, parameters) {
  var authSnippet = _.assign(
    {},
    parseConnectionStringPassword(url.password(connectionUrl)),
    parseConnectionStringUsername(url.username(connectionUrl))
  );
 
  return _.assign(
    parameters,
    {
      url: url.base(connectionUrl),
    },
    _.keys(authSnippet).length
      ? {
          auth: authSnippet,
        }
      : {},
    parseConnectionParameters()
  );
}
 
/**
 * Try to get connection settings parameters from the passed object
 *
 * @param {Object} connectionSettings - object which should contain connection settings
 * @param {Object} parameters - reference to parameter structure which is updated by method
 */
function parseConnectionSettings(connectionSettings, parameters) {
  if (_.isObject(connectionSettings.auth)) {
    parameters.auth = connectionSettings.auth;
  }
 
  if (_.isPlainObject(connectionSettings.parameters)) {
    parameters.parameters = _.assign(
      parameters.parameters,
      connectionSettings.parameters
    );
  }
 
  if (_.isObject(connectionSettings.logger)) {
    parameters.logger = connectionSettings.logger;
  }
 
  if (_.isString(connectionSettings.annotationsUrl)) {
    parameters.annotationsUrl = connectionSettings.annotationsUrl;
  }
}
 
/**
 * Try to get all needed url parameters from the passed object
 *
 * @param {Object} connectionSettings - string which could contains corrently defined url
 * @param {Object} parameters - reference to parameter structure which is updated by method
 *
 * @return {Object} returns structure defining OData endpoint
 */
function parseConnectionObject(connectionSettings, parameters) {
  if (!_.isString(connectionSettings.url)) {
    throw new Error("URL is missing in connection settings.");
  }
 
  parseConnectionString(connectionSettings.url, parameters);
  parseConnectionSettings(connectionSettings, parameters);
 
  return parameters;
}
 
/**
 * Parse connection settings passed to the client object
 *
 * @param {String|Object} connectionSettings - url or object with url and auth settings
 *
 * @return {Object} structure used by the client to connect the server
 */
function parseSettings(connectionSettings = process.env.ODATA_URL) {
  var parameters = {
    url: null,
    strict:
      !_.isBoolean(connectionSettings.strict) || connectionSettings.strict,
  };
 
  if (_.isString(connectionSettings) && connectionSettings) {
    parameters = parseConnectionString(connectionSettings, parameters);
  } else if (_.isObject(connectionSettings)) {
    parameters = parseConnectionObject(
      _.assign(
        {
          url: process.env.ODATA_URL,
        },
        connectionSettings
      ),
      parameters
    );
  } else {
    throw new Error("Invalid OData service connection settings");
  }
 
  parameters = parseSettings._.parseConnectionCookie(
    connectionSettings,
    parameters
  );
 
  parameters = parseSettings._.parseTLSDefinitions(
    parseSettings.AUTH.CERT,
    connectionSettings,
    process.env,
    parameters
  );
 
  parameters = parseSettings._.parseHeadersDefinitions(
    connectionSettings,
    process.env,
    parameters
  );
 
  return parameters;
}
 
parseSettings._ = {};
 
/**
 * Try to get authentication headers from constructor settings and environment variable
 *
 * @param {Object} connectionSettings - object which could contains corrently defined url
 * @param {Object} environmentVariables - map of environment variables
 * @param {Object} parameters - reference to parameter structure which is updated by method
 *
 * @return {Object} returns structure defining OData endpoint
 */
parseSettings._.parseHeadersDefinitions = function (
  connectionSettings,
  environmentVariables,
  parameters
) {
  const isValidHeadersSettings = parseSettings._.checkHeadersSettings(
    connectionSettings,
    environmentVariables
  );
 
  if (isValidHeadersSettings === false) {
    throw new Error("Invalid settings for headers authentication");
  }
 
  if (isValidHeadersSettings === true) {
    if (_.has(connectionSettings, "auth.headers")) {
      _.set(parameters, "auth.headers", connectionSettings.auth.headers);
      _.set(parameters, "auth.type", "headers");
    } else if (environmentVariables.ODATA_HEADERS) {
      _.set(
        parameters,
        "auth.headers",
        JSON.parse(environmentVariables.ODATA_HEADERS)
      );
      _.set(parameters, "auth.type", "headers");
    }
  }
 
  return parameters;
};
 
/**
 * Check if authentication headers settings is correct
 *
 * @param {Object} connectionSettings - object which could contains corrently defined url
 * @param {Object} environmentVariables - map of environment variables
 *
 * @return {Object} returns structure defining OData endpoint
 */
parseSettings._.checkHeadersSettings = function (
  connectionSettings,
  environmentVariables
) {
  let check = null;
 
  if (_.has(connectionSettings, "auth.headers")) {
    check = _.isObject(connectionSettings.auth.headers);
  } else if (_.has(environmentVariables, "ODATA_HEADERS")) {
    try {
      check = _.isObject(JSON.parse(environmentVariables.ODATA_HEADERS));
    } catch (err) {
      check = false;
    }
  }
 
  return check;
};
 
/**
 * Try to get cookies from environment variable
 *
 * @param {Object} connectionSettings - object which could contains corrently defined url
 * @param {Object} parameters - reference to parameter structure which is updated by method
 *
 * @return {Object} returns structure defining OData endpoint
 */
parseSettings._.parseConnectionCookie = function parseConnectionCookie(
  connectionSettings,
  parameters
) {
  let cookies;
 
  if (parseSettings._.checkCookieSettings(connectionSettings) === false) {
    throw new Error("Invalid authenticate cookie settings");
  }
 
  if (_.has(connectionSettings, "auth.cookies")) {
    _.set(parameters, "auth.cookies", connectionSettings.auth.cookies);
    _.set(parameters, "auth.type", "cookie");
  } else if (process.env.ODATA_COOKIE) {
    try {
      cookies = JSON.parse(process.env.ODATA_COOKIE);
    } catch (err) {
      cookies = [process.env.ODATA_COOKIE];
    }
    _.set(parameters, "auth.cookies", cookies);
    _.set(parameters, "auth.type", "cookie");
  }
 
  return parameters;
};
 
/**
 * Check if cookie settings is correct
 *
 * @param {Object} connectionSettings - object which could contains corrently defined url
 *
 * @return {Object} returns structure defining OData endpoint
 */
parseSettings._.checkCookieSettings = function (connectionSettings) {
  let check = true;
 
  if (_.has(connectionSettings, "auth.cookies")) {
    check =
      _.isArray(connectionSettings.auth.cookies) &&
      connectionSettings.auth.cookies.every((cookie) => _.isString(cookie));
  } else if (_.has(process.env, "ODATA_COOKIE")) {
    try {
      let cookieToCheck = JSON.parse(process.env.ODATA_COOKIE);
      check = _.isArray(cookieToCheck);
    } catch (err) {
      check = _.isString(process.env.ODATA_COOKIE);
    }
  }
 
  return check;
};
 
parseSettings.AUTH = {
  CERT: {
    PEM_OBJECT_KEYS: {
      ORDER: 1,
      SOURCE: "SETTINGS",
      MANDATORY_KEYS: ["auth.cert", "auth.key"],
      OPTIONAL_KEYS: ["auth.ca"],
      ADDITIONAL_KEYS: {
        "auth.type": "cert",
      },
    },
    PFX_OBJECT_KEYS: {
      ORDER: 2,
      SOURCE: "SETTINGS",
      MANDATORY_KEYS: ["auth.pfx", "auth.passphrase"],
      OPTIONAL_KEYS: ["auth.ca"],
      ADDITIONAL_KEYS: {
        "auth.type": "cert",
      },
    },
    PEM_ENVIRONMENT_KEYS: {
      ORDER: 3,
      SOURCE: "ENV",
      MANDATORY_KEYS: ["ODATA_CLIENT_CERT", "ODATA_CLIENT_KEY"],
      OPTIONAL_KEYS: ["ODATA_EXTRA_CA"],
      CONVERSION: {
        ODATA_CLIENT_CERT: "auth.cert",
        ODATA_CLIENT_KEY: "auth.key",
        ODATA_EXTRA_CA: "auth.ca",
      },
      ADDITIONAL_KEYS: {
        "auth.type": "cert",
      },
    },
    CA_OBJECT_KEYS: {
      ORDER: 4,
      SOURCE: "SETTINGS",
      MANDATORY_KEYS: ["auth.ca"],
      OPTIONAL_KEYS: [],
    },
    CA_ENVIRONMENT_KEYS: {
      ORDER: 5,
      SOURCE: "ENV",
      MANDATORY_KEYS: ["ODATA_EXTRA_CA"],
      OPTIONAL_KEYS: [],
      CONVERSION: { ODATA_EXTRA_CA: "auth.ca" },
    },
  },
};
 
/**
 * Determine type of template from AUTH.CERT for
 * checking and parsing TLS definitions
 *
 * @param {Array} templateDefinitions - list of templates for TLS definitionis (coming from AUTH.CERT)
 * @param {Object} connectionSettings - object which could contains corrently defined url
 * @param {Object} processEnv - map of environment variables
 *
 * @return {Object} template TLS settings
 */
parseSettings._.determineTLSDefinition = function (
  templateDefinitions,
  connectionSettings,
  processEnv
) {
  return _.map(templateDefinitions, (def, key) =>
    _.assign(
      {
        key: key,
        source: def.SOURCE === "ENV" ? processEnv : connectionSettings,
      },
      def
    )
  )
    .sort((defA, defB) => defA.ORDER - defB.ORDER)
    .find((def) => def.MANDATORY_KEYS.some((key) => _.has(def.source, key)));
};
 
/**
 * Check current TLS settings by template
 *
 * @param {Array} definition - list of templates for TLS definitionis (coming from AUTH.CERT)
 * @param {Object} connectionSettings - object which could contains corrently defined url
 * @param {Object} processEnv - map of environment variables
 * @param {Object} parameters - parsed settings
 *
 * @return {Error} error description
 */
parseSettings._.checkTLSDefinition = function (
  definition,
  connectionSettings,
  processEnv,
  parameters
) {
  let error;
 
  if (definition) {
    if (!(_.get(parameters, "url") || "").match(/^https/)) {
      error = new Error("Use SSL parameters with HTTPS only.");
    } else {
      const missingKeys = definition.MANDATORY_KEYS.filter(
        (mandatoryKey) => !_.has(definition.source, mandatoryKey)
      );
      Eif (missingKeys.length > 0) {
        error = new Error(`Missing certificate parameter ${missingKeys[0]}.`);
      }
    }
  }
 
  return error;
};
 
/**
 * Parse TLS settings
 *
 * @param {Array} templateDefinitions - list of templates for TLS definitionis (coming from AUTH.CERT)
 * @param {Object} connectionSettings - object which could contains corrently defined url
 * @param {Object} processEnv - map of environment variables
 * @param {Object} parameters - parsed settings
 *
 * @return {Object} parameters with TLS settings
 */
parseSettings._.parseTLSDefinitions = function (
  templateDefinitions,
  connectionSettings,
  processEnv,
  parameters
) {
  const definition = parseSettings._.determineTLSDefinition(
    templateDefinitions,
    connectionSettings,
    processEnv
  );
 
  const err = parseSettings._.checkTLSDefinition(
    definition,
    connectionSettings,
    processEnv,
    parameters
  );
 
  if (err) {
    throw err;
  } else if (definition) {
    _.concat([], definition.MANDATORY_KEYS, definition.OPTIONAL_KEYS)
      .filter((path) => _.has(definition.source, path))
      .forEach((sourcePath) => {
        const destinationPath = _.has(definition, "CONVERSION." + sourcePath)
          ? definition.CONVERSION[sourcePath]
          : sourcePath;
        _.set(
          parameters,
          destinationPath,
          _.get(definition.source, sourcePath)
        );
      });
    _.each(definition.ADDITIONAL_KEYS, (value, path) =>
      _.set(parameters, path, value)
    );
  }
 
  return parameters;
};
 
module.exports = parseSettings;