/**
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 Builder = require('../../../attack-patterns');
const { SCORES } = require('../../../common');

const COMPARISON_OPERATORS = ['==', '>=', '>', '<', '<=', '!=='];
const MAX_ALLOWED_OR_CONDITION_DISTANCE = 10;

const operatorsPatternText = COMPARISON_OPERATORS.map(
  (chars) => `(${chars})`
).join('|');

const commentsSearch = /\/\/|<--/;

const quoteSearch = Builder()
  .whitespaces()
  .quote()
  .oneOrMoreOf()
  .alphanumeric()
  .quote()
  .whitespaces()
  .literally(`(${operatorsPatternText})`, true)
  .whitespaces()
  .quote()
  .oneOrMoreOf()
  .alphanumeric()
  .quote()
  .build();

const numericSearch = Builder()
  .whitespaces()
  .oneOrMoreOf()
  .alphanumeric()
  .whitespaces()
  .literally(`(${operatorsPatternText})`, true)
  .whitespaces()
  .oneOrMoreOf()
  .alphanumeric()
  .build();

/**
 * Checks the index from the end of the or-search and
 * makes sure it's within reasonable limits.
 * @param {number} matchIndex
 * @returns {boolean}
 */
const matchIndexInLimit = (matchIndex) =>
  matchIndex < MAX_ALLOWED_OR_CONDITION_DISTANCE;

/**
 * Does the string have any comments?
 * @param {string} string
 * @returns {boolean}
 */
const hasComments = (string) => commentsSearch.test(string);

class SimpleOrSearcher {
  constructor() {
    this.id = 'TRUING_STRING_INJ';
    this.name = 'SimpleOrSearcher';
  }

  /**
   * @param {Object} userInput
   * @param {string} userInput.value
   * @returns {string}
   */
  getImpact(userInput) {
    let found = false;

    const orSearch = Builder({ flags: 'gim' })
      .whitespacesRequired()
      .literally('||')
      .whitespacesRequired()
      .build();

    while (orSearch.exec(userInput.value)) {
      const afterOrSegment = userInput.value.substring(orSearch.lastIndex);
      const quotedStringIndex = afterOrSegment.search(quoteSearch);
      if (0 <= quotedStringIndex) {
        if (matchIndexInLimit(quotedStringIndex)) found = true;
        if (hasComments(afterOrSegment)) {
          return SCORES.CRITICAL;
        }
      }

      const numericIndex = afterOrSegment.search(numericSearch);
      if (0 <= numericIndex) {
        if (matchIndexInLimit(numericIndex)) found = true;
        if (hasComments(afterOrSegment)) {
          return SCORES.CRITICAL;
        }
      }
    }

    // If we found matches, just not with comments, we still score
    return found ? SCORES.HIGH : SCORES.NONE;
  }
}

module.exports = new SimpleOrSearcher();
