/**
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.
*/
/**
 * @module lib/rules/protect/untrusted-deserialization/Rule
 */

'use strict';

const Rule = require('../');
const constants = require('../../../constants');
const UserInput = require('../../../reporter/models/app-activity/user-input');

const { SINK_TYPES, INPUT_TYPES, IMPORTANCE } = constants;

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

    this.id = 'untrusted-deserialization';
    this.name = 'Untrusted Deserialization';

    this.applicableInputs = [
      INPUT_TYPES.BODY,
      INPUT_TYPES.COOKIE_VALUE,
      INPUT_TYPES.HEADER,
      INPUT_TYPES.JSON_VALUE,
      INPUT_TYPES.PARAMETER_VALUE,
      INPUT_TYPES.QUERYSTRING,
      INPUT_TYPES.URL,
      INPUT_TYPES.URL_PARAMETER
    ];

    this.applicableSinks = [SINK_TYPES.DESERIALIZED_STRING];
  }

  /**
   * By returning `false` this rule will bypass input classification stage.
   * @returns {boolean}
   */
  appliesToInputType(type, name) {
    return false;
  }

  /**
   * Evaluate the data from the sink event and assess whether there is an exploit.
   * @param {ApplicationContext} event
   */
  evaluateAtSink({ event, request, samples }) {
    const { data } = event;
    const containsToken = 0 <= data.indexOf('_$$ND_FUNC$$_'); // vulnerable token
    if (containsToken) {
      const input = new UserInput({
        value: data,
        type: INPUT_TYPES.UNKNOWN
      });
      const sample = this.createAndSaveSample({
        input,
        attributes: { effective: true },
        classification: IMPORTANCE.DEFINITE,
        event,
        samples,
        request
      });

      this.appendAttackDetails(sample, {
        command: false,
        deserializer: event.id
      });
      this.blockRequest(sample);
    }
  }

  /**
   * Builds the details for the report.
   * @param {Sample} sample The sample on which do build details
   * @param {Object} findings The findings from the sink evaluation
   */
  buildDetails(sample, findings) {
    return findings;
  }
}

module.exports = UntrustedDeserializationRule;
