# Copyright (c) 2023 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details. # frozen_string_literal: true require 'contrast/agent/protect/rule/input_classification/encoding_rates' require 'contrast/agent/telemetry/input_analysis_encoding_event' require 'contrast/components/logger' module Contrast module Agent module Protect module Rule module InputClassification # This class will safe all the information for the Base64 decoding matches per input type. class Base64Statistic include Contrast::Components::Logger::InstanceMethods # @return [Hash] attr_reader :data # Capacity for request context life cycle. CAPACITY = 1000 def initialize @data = {} end # Add a match for the given input type. # # @param input_type [Symbol] def match! input_type return @data[input_type]&.increase_match_base64 if @data[input_type] @data[input_type] = Contrast::Agent::Protect::Rule::InputClassification::EncodingRates.new(input_type) @data[input_type].increase_match_base64 end # Add a mismatch for the given input type. # # @param input_type [Symbol] def mismatch! input_type return @data[input_type]&.increase_mismatch_base64 if @data[input_type] @data[input_type] = Contrast::Agent::Protect::Rule::InputClassification::EncodingRates.new(input_type) @data[input_type].increase_mismatch_base64 end # Clears statistic data. def clear @data.clear end # @return [Array] the events to be sent. def to_events events = [] data.each do |_input_type, encoding_rate| event = Contrast::Agent::Telemetry::InputAnalysisEncodingEvent.new(nil, encoding_rate) next if event.empty? events << event end events rescue StandardError => e logger.error("[Telemetry] Error while creating events: #{ e }", stacktrace: e.backtrace) [] end end end end end end end