All files / lib/agent authentication.js

100% Statements 45/45
100% Branches 20/20
100% Functions 7/7
100% Lines 45/45

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    1x   1x                 1x                                       1x     3x 2x 2x 1x   1x         1x     3x                                     1x 4x   4x       2x 2x     2x             2x                                                     1x       9x 9x 9x 9x   9x 9x   3x     3x     6x       6x 1x   5x       5x 4x 4x     4x                     1x                                                 1x   9x 4x 1x     3x 1x     2x 1x         9x    
"use strict";
 
const _ = require("lodash");
 
exports.AUTHENTICATORS = {
  basic: require("./authentication/basic"),
  none: require("./authentication/none"),
  samlSap: require("./authentication/samlSap"),
  cookie: require("./authentication/cookie"),
  cert: require("./authentication/cert"),
  headers: require("./authentication/headers"),
};
 
exports.AUTHENTICATORS_AUTO_ORDER = [
  exports.AUTHENTICATORS.samlSap,
  exports.AUTHENTICATORS.basic,
  exports.AUTHENTICATORS.none,
];
 
/**
 * Authenticate user by different ways defined
 * by settings
 *
 * @param {Agent} agent instance of agent/Agent class which
 *        is authorized
 * @param {String} endpointUrl url of metadata, which is used as
 *        root of service
 *
 * @return {Promise} promise which is resolve when first authenticator succeed
 *        or reject if all authenticators fails
 *
 * @public
 */
exports.authenticate = function (agent, endpointUrl) {
  let promise;
 
  if (_.has(agent, "settings.auth.type")) {
    const authenticator = exports.AUTHENTICATORS[agent.settings.auth.type];
    if (authenticator) {
      promise = authenticator(agent.settings, agent, endpointUrl);
    } else {
      promise = Promise.reject(
        new Error(`Missing authenticator type ${agent.settings.auth.type}`)
      );
    }
  } else {
    promise = exports.authenticateAuto(agent, endpointUrl);
  }
 
  return promise;
};
 
/**
 * Authenticate user by authenticators. Authenticators are modules
 * in lib/agent/authentication/. List of modules is in Agent.authenticators
 * array. Authenticate method calls authenticators in order of list.
 * User is authenticated when first authenticator succeed.
 *
 * @param {Agent} agent instance of agent/Agent class which
 *        is authorized
 * @param {String} endpointUrl url of metadata, which is used as
 *        root of service
 *
 * @return {Promise} promise which is resolve when first authenticator succeed
 *        or reject if all authenticators fails
 *
 * @public
 */
exports.authenticateAuto = function (agent, endpointUrl) {
  return new Promise((resolve, reject) => {
    let authenticator;
    if (
      _.isArray(exports.AUTHENTICATORS_AUTO_ORDER) &&
      exports.AUTHENTICATORS_AUTO_ORDER.length > 0
    ) {
      authenticator = exports.AUTHENTICATORS_AUTO_ORDER[0];
      agent.logger.debug(
        `Try to authenticate over ${authenticator.authenticatorName} authenticator.`
      );
      exports.tryAuthenticator(1, endpointUrl, {
        authentcatePromise: authenticator(agent.settings, agent, endpointUrl),
        success: resolve,
        error: reject,
        agent: agent,
      });
    } else {
      reject(new Error("Authenticators are not defined."));
    }
  });
};
 
/**
 * Try authenticate user by particular authenticator. If authenticator
 * fails try to use next authenticator from Agent.authenticators list.
 * If all authenticators fails call callBackError parameter if any
 * authenticator succeed call callBack parameter
 *
 * The method is used internally in the public authenticated method
 *
 * @private
 *
 * @param {Number} index to the Agent.authenticators which is used
 * @param {String} endpointUrl url of metadata, which is used as
 *        root of service
 * @param {Object} init map with additonal parameters
 *        authentcatePromise - previous authenticator promise
 *                 determine previous authenticator result
 *        success - function which is called when authenticator
 *                 succeed
 *        error - function which is called when all authenticators
 *                 fails
 * @private
 */
exports.tryAuthenticator = function (index, endpointUrl, init) {
  let previousAuthenticator;
  let authenticator;
 
  const previousAuthenticatorPromise = init.authentcatePromise;
  const callBack = init.success;
  const callBackError = init.error;
  const agent = init.agent;
 
  previousAuthenticator = exports.AUTHENTICATORS_AUTO_ORDER[index - 1];
  previousAuthenticatorPromise
    .then((response) => {
      agent.logger.debug(
        `Authenticator ${previousAuthenticator.authenticatorName} succeed.`
      );
      callBack(response);
    })
    .catch((err) => {
      let fatalError = exports.fatalAuthenticateError(
        err,
        previousAuthenticator
      );
      if (fatalError) {
        callBackError(fatalError);
      } else {
        agent.logger.warn(
          `Authenticator ${previousAuthenticator.authenticatorName} failed.`,
          err
        );
        if (index < exports.AUTHENTICATORS_AUTO_ORDER.length) {
          authenticator = exports.AUTHENTICATORS_AUTO_ORDER[index];
          agent.logger.debug(
            `Try to authenticate over ${authenticator.authenticatorName} authenticator.`
          );
          exports.tryAuthenticator(++index, endpointUrl, {
            authentcatePromise: authenticator(
              agent.settings,
              agent,
              endpointUrl
            ),
            success: callBack,
            error: callBackError,
            agent: agent,
          });
        } else {
          callBackError(
            new Error(`Not valid authenticator found - ${err.message}.`)
          );
        }
      }
    });
};
 
/**
 * Try authenticate user by particular authenticator. If authenticator
 * fails try to use next authenticator from Agent.authenticators list.
 * If all authenticators fails call callBackError parameter if any
 * authenticator succeed call callBack parameter
 *
 * The method is used internally in the public authenticated method
 *
 * @private
 *
 * @param {Error} resError error based on the response
 * @param {Object} previousAuthenticator authenticator object
 *
 * @returns {Error} returns object with fatal error which steps authentication
 *
 * @private
 */
exports.fatalAuthenticateError = function (resError, previousAuthenticator) {
  let fatalError;
  if (!resError.unsupported) {
    if (resError.response === undefined) {
      fatalError = new Error(
        `Authenticator ${previousAuthenticator.authenticatorName}: fatal error: ${resError}`
      );
    } else if (resError.response.forbidden) {
      fatalError = new Error(
        `Authenticator ${previousAuthenticator.authenticatorName}: forbidden: ${resError.response.res.text}`
      );
    } else if (resError.response.serverError) {
      fatalError = new Error(
        `Authenticator ${previousAuthenticator.authenticatorName}: server error: ${resError.response.res.text}`
      );
    }
  }
  return fatalError;
};