Sha256: ed49a12ad053cd9e32e4dcd5225ea0ca644b42313650249c1c1d28324b4ca992

Contents?: true

Size: 1.81 KB

Versions: 1

Compression:

Stored size: 1.81 KB

Contents

# Copyright (c) 2023 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
# frozen_string_literal: true

require 'json'
require 'contrast/utils/hash_utils'
require 'contrast/components/logger'

module Contrast
  module Utils
    # Module to hold Agent's custom JSON.parse logic.
    module Json
      class << self
        include Contrast::Components::Logger::InstanceMethods

        # Add any known cases where parsing error might arise from older json parser:
        # @return [Array<String>]
        SPECIAL_CASES = [nil, "", "\"\"", "\"0\""].cs__freeze # rubocop:disable Style/StringLiterals

        # Parses a string using JSON.parser. This method is used instead of standard JSON.parse to
        # support older versions of json gem => not supporting key-value second parameter, which is
        # supported after json 2.3.0.
        #
        # @param string [String]
        # @param deep_symbolize [Boolean] flag to set if keys needs to be deep symbolized.
        # @return [Hash]
        def parse string, deep_symbolize: false
          # The Agent receives empty responses from TS sometimes.
          # There is a special case to handle this.
          return {} if SPECIAL_CASES.include?(string)

          symbolized_hash = {}
          hash = JSON::Parser.new(string).parse
          symbolized_hash = Contrast::Utils::HashUtils.deep_symbolize_all_keys(hash) if deep_symbolize
          return hash unless deep_symbolize

          symbolized_hash
        rescue JSON::ParserError => e
          # Any parsing error will produce empty {}. Since older JSON might pose support issues with newer Ruby,
          # We might just log any miss-parsings and allow Agent to continue.
          logger.warn("[JSON] parse error: #{ e }")
          {}
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
contrast-agent-7.6.1 lib/contrast/utils/json.rb