/**
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';
/**
 * @module lib/assess/response-scanning/headers/csp-header-insecure
 */
const _ = require('lodash');
const parse = require('content-security-policy-parser');
const { getCspHeaders } = require('./csp-utils');
const agentEmitter = require('../../../agent-emitter');

const RULE_ID = 'csp-header-insecure';
const DEFAULT = 'default-src';

/**
 * Special evaluator for any -src directives
 * If it is empty and default is secure then it is secure
 *
 * @param {Array} sources sources for a given -src directive
 * @param {Array} defaultSources sources for the default-src directive
 * @return {Boolean}
 */
function isSrcSecure(sources, defaultSources) {
  return sources.length === 0
    ? isSourceSecure(defaultSources)
    : isSourceSecure(sources);
}

/**
 * Checks if a given source(s) for a directive is defined and is secure(does not contain a '*')
 *
 * @param {Array} sources sources for a given csp directive
 * @return {Boolean} whether a directive is secure
 */
function isSourceSecure(sources) {
  return (
    sources.length > 0 &&
    sources.every((source) => !!source && !/\*/.test(source))
  );
}

/**
 * Evaluator for reflected-xss directive.  Checks if the value is not
 * equal to 1
 * Note: If empty it is secure
 * @param {Array} sources sources for a given csp directive
 * @return {Boolean} whether a directive is secure
 */
function xssCheck(sources) {
  return sources.every((source) => parseInt(source) === 1);
}

/**
 * Evaluator for referrer directive. Checks if value is not *
 * or contains unsafe-url
 * @param {Array} sources sources for a given csp directive
 * @return {Boolean} whether a directive is secure
 */
function referrerCheck(sources) {
  return sources.every((source) => !/unsafe-url/.test(source));
}

const KNOWN_DIRECTIVES = [
  { name: 'default-src', evaluator: isSourceSecure },
  { name: 'base-uri', evaluator: isSourceSecure },
  { name: 'child-src' },
  { name: 'connect-src' },
  { name: 'frame-src' },
  { name: 'media-src' },
  { name: 'object-src' },
  { name: 'script-src' },
  { name: 'style-src' },
  { name: 'form-action', evaluator: isSourceSecure },
  { name: 'frame-ancestors', evaluator: isSourceSecure },
  { name: 'plugin-types', evaluator: isSourceSecure },
  { name: 'reflected-xss', evaluator: xssCheck },
  { name: 'referrer', evaluator: referrerCheck }
];

/**
 * Terminology
 * See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
 *  csp - Content Security Policy
 *  policy - the entire csp header value
 *  directive - a specific key of the policy(e.g default-src, media-src)
 *  sources - the value(s) of the directive(default-src foobar.com;)
 */

/**
 * Convenience method for formatting a given directive's
 * secure and value properties. It also camel cases the key
 * to match the spec for the rule's finding
 *
 * @param {Object} params
 * @param {Object} params.data obj to store the full props object
 * @param {String} params.key the csp header directive
 * @param {Array} params.value array of sources for the directive
 * @param {Boolean} params.isSecure flag indicating if directive is secure
 */
function formatSource({
  data,
  key,
  sources = [],
  defaultSources = [],
  evaluator = isSrcSecure
}) {
  key = _.camelCase(key);
  const evaluation = evaluator(sources, defaultSources);
  if (!evaluation && !data.insecure) {
    data.insecure = true;
  }
  data[`${key}Secure`] = evaluation;

  data[`${key}Value`] = sources.join(' ');
}

/**
 * This will parse a CSP header value into an object
 * It will then iterate over all known keys and build
 * which are secure and which aren't with the values
 * for each. If a directive is undefined, it assumed
 * insecure and will provide '' as the value
 *
 * See: https://contrast.atlassian.net/wiki/spaces/ENG/pages/805503460/Content-Security-Policy+Header+Misconfigured
 */
function checkCspSources(policy) {
  const csp = parse(policy);
  const data = {};

  KNOWN_DIRECTIVES.forEach(({ name, evaluator }) => {
    const sources = csp[name];
    formatSource({
      data,
      defaultSources: csp[DEFAULT],
      key: name,
      sources,
      evaluator
    });
  });

  return data;
}

/**
 * Checks the response headers for the CSP. If found, and insecure, will return
 * the evidence for reporting.
 *
 * @param   {Object}        responseHeaders - HTTP headers object.
 * @returns {Object}                        - Evidence for insecure CSP header.
 */
function check(responseHeaders) {
  const cspHeaders = getCspHeaders(responseHeaders);

  // Don't report if not set; this report belongs to 'csp-header-missing'
  if (!cspHeaders) {
    return false;
  }

  const data = checkCspSources(cspHeaders);

  if (data.insecure) {
    // The TS API is expecting this with a typo
    // temporary we'll send it like this until it is
    // fixed on their side
    data.refererSecure = data.referrerSecure;
    data.refererValue = data.referrerValue;

    delete data.insecure;
    delete data.referrerSecure;
    delete data.referrerValue;

    return data;
  }
}

module.exports = ({ common }) => ({
  handle(rule) {
    agentEmitter.on(
      'send',
      function({ request, responseHeaders }) {
        const trigger = check(responseHeaders);

        if (trigger) {
          common.emitFinding({
            request,
            props: { data: JSON.stringify(trigger) },
            ruleId: RULE_ID
          });
        }
      },
      rule
    );
  }
});
module.exports.formatSource = formatSource;
module.exports.check = check;
module.exports.KNOWN_DIRECTIVES = KNOWN_DIRECTIVES;
