/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';

const UserInput = require('../../../reporter/models/app-activity/user-input');
const Sample = require('../../../reporter/models/app-activity/sample');
const { IpAnalyzer } = require('../../../util/ip-analyzer');
const {
  INPUT_TYPES,
  IMPORTANCE,
  PROTECTION_MODES,
  RULES: { IP_DENYLIST }
} = require('../common');
const Rule = require('../');

class IpDenylistRule extends Rule {
  constructor(policy, agent) {
    super(policy, agent);
    this._analyzer = new IpAnalyzer(policy.data);
    // TODO: This should go away with CONTRAST-34184
    this._analyzer.on('expired', (expired) => {
      const { settings } = this._analyzer;
      this._analyzer.updateSettings(
        settings.filter((setting) => setting.uuid !== expired.uuid)
      );
    });
    this.blockAtEntry = true;
    this.id = IP_DENYLIST;
    this.name = 'IP Denylist';
    this.applicableInputs = [INPUT_TYPES.IP, INPUT_TYPES.HEADER];
    this.mode = PROTECTION_MODES.BLOCK_AT_PERIMETER;
  }

  /**
   * Custom for this rule.
   * @param {} req
   * @returns {}
   */
  getEvaluator() {
    return this._analyzer;
  }

  /**
   * Evalutates header and IP <code>UserInput</code> values.
   * @param {UserInput[]} userInputs
   */
  preFilterUserInput(userInput, sourceEvent, samples) {
    const evaluator = this.getEvaluator();

    const evaluation = evaluator.evaluate(userInput);
    if (evaluation) {
      const sample = this.addSample(evaluation, sourceEvent, samples);
      this.blockRequest(sample);
    }
  }

  /**
   * Uses the evaluation to build out the sample and append to its collection.
   * @param {Object} evaluation Returned by <code>analyzer.match</code>.
   */
  addSample(evaluation, sourceEvent, samples) {
    const sample = new Sample(
      new UserInput({
        name: 'IP Address',
        type: INPUT_TYPES.UNKNOWN,
        value: evaluation.match
      }),
      sourceEvent
    );

    sample.confirmedAttack = true;
    sample.details = this.buildDetails(sample, evaluation);
    sample.effective = false;

    samples.addRawSample(this.id, sample, IMPORTANCE.DEFINITE);

    return sample;
  }

  /**
   * Builds the details for sample.
   * @param   {Sample} sample     The collected sample.
   * @param   {Object} evaluation IpAnalyzer result.
   * @returns {Object}
   */
  buildDetails(sample, evaluation) {
    return {
      ip: evaluation.ip,
      uuid: evaluation.uuid
    };
  }
}

module.exports = IpDenylistRule;
