/**
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 Evaluator = require('./evaluator');
const { INPUT_TYPES, SINK_TYPES, IMPORTANCE } = require('../common');
const Sample = require('../../../reporter/models/app-activity/sample');

class MethodTamperingRule extends Rule {
  constructor(policy) {
    super(policy);

    // Common Rule configuration values
    this.applicableInputs = [INPUT_TYPES.METHOD];
    this.applicableSinks = [SINK_TYPES.RESPONSE_STATUS];
    this.id = 'method-tampering';
    this.name = 'HTTP Method Tampering';
  }

  preFilterUserInput(input, sourceEvent, samples) {
    const method = input.value;
    const uri = _.get(sourceEvent, 'request.uri');
    const headers = _.get(sourceEvent, 'request.headers');
    if (Evaluator.isTampered({ headers, uri, method })) {
      const sample = this.addSample(input, sourceEvent, samples);

      if (this.blockAtEntry) {
        this.blockRequest(sample);
      }
    }
  }

  evaluateAtSink({ event, applicableSamples }) {
    if (_.isEmpty(applicableSamples)) {
      return;
    }

    const sample = applicableSamples.values().next().value;
    const statusCode = event.data;

    if (statusCode < 400) {
      sample.effective = true;
    }

    sample.captureAppContext(event);
    sample.details = MethodTamperingRule.buildDetails(
      sample.input.value,
      statusCode
    );

    this.blockRequest(sample);
  }

  addSample(input, sourceEvent, samples) {
    const sample = new Sample(input, sourceEvent);
    sample.confirmedAttack = true;
    sample.details = MethodTamperingRule.buildDetails(input.value);
    samples.addRawSample(this.id, sample, IMPORTANCE.DEFINITE);

    return sample;
  }

  buildBaseEvent(sample) {
    return {
      ruleId: this.id,
      // for CEF extensions
      outcome: this.getAttackStatus(sample),
      pri: this.id,
      request: _.get(sample, 'request.uri', '').replace(' ', '<space>'),
      requestMethod: _.get(sample, 'request.method'),
      src: sample.request.ip,
      value: sample.details
    };
  }

  static buildDetails(method, responseCode) {
    return {
      method,
      responseCode: responseCode || 403
    };
  }
}

module.exports = MethodTamperingRule;
