/**
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 _ = require('lodash');
const Rule = require('../');
const Sample = require('../../../reporter/models/app-activity/sample');
const utils = require('./index');
const { INPUT_TYPES, IMPORTANCE, PROTECTION_MODES } = require('../common');

const USER_AGENT = 'user-agent';

class BotBlockerRule extends Rule {
  constructor(policy = {}, agent) {
    super(policy, agent);
    this.id = 'bot-blocker';
    this.name = 'Bot Blocker';
    this.blockAtEntry = true;
    this.mode = PROTECTION_MODES.BLOCK_AT_PERIMETER;
    this.applicableInputs = [INPUT_TYPES.HEADER];

    this.usesLibInputAnalysis = true;
  }

  /**
   * Checks whether the header's user-agent is a known bot.
   * @param {Object} data The request headers
   * @param {String} type Source type (HEADERS)
   */
  preFilterUserInput(input, sourceEvent, samples) {
    if (!input || input.name !== USER_AGENT) {
      return;
    }

    const results = {
      input,
      finding: utils.isKnownBot(input.value)
    };

    if (results.finding) {
      const sample = this.addSample(
        results.input,
        results.finding,
        sourceEvent,
        samples
      );
      this.blockRequest(sample);
    }
  }

  /**
   * Returns true only when given params HEADER and User-Agent.
   * @param   {String}  type The input type
   * @param   {String}  name The input type name
   * @returns {Boolean}
   */
  appliesToInputType(type, name) {
    const appliesToType = type === INPUT_TYPES.HEADER;

    return name
      ? appliesToType && name.toLowerCase() === USER_AGENT
      : appliesToType;
  }

  /**
   * Creates and adds a sample to the rule's collection.
   * @param {Object} input    Shallow user input DTM
   * @param {Object} findings Bot signature findings
   */
  addSample(input, findings, sourceEvent, samples) {
    const sample = new Sample(input, sourceEvent);

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

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

    return sample;
  }

  /**
   * Builds the details for the sample.
   * @param   {Sample} sample   Sample instance.
   * @param   {Object} findings Bot signature findings
   * @returns {Object}
   */
  buildDetails(sample, findings) {
    return {
      bot: findings.startsWith || findings.includes,
      userAgent: _.get(sample, 'input.value')
    };
  }
}

module.exports = BotBlockerRule;
