mirror of
https://github.com/lingble/chatwoot.git
synced 2025-11-03 04:27:53 +00:00
chore: Add max length validation to text fields (#7073)
Introduces a default max length validation for all string and text fields to prevent processing large payloads.
This commit is contained in:
@@ -34,7 +34,7 @@ class Account < ApplicationRecord
|
||||
|
||||
validates :name, presence: true
|
||||
validates :auto_resolve_duration, numericality: { greater_than_or_equal_to: 1, less_than_or_equal_to: 999, allow_nil: true }
|
||||
validates :name, length: { maximum: 255 }
|
||||
validates :domain, length: { maximum: 100 }
|
||||
|
||||
has_many :account_users, dependent: :destroy_async
|
||||
has_many :agent_bot_inboxes, dependent: :destroy_async
|
||||
|
||||
@@ -2,6 +2,8 @@ class ApplicationRecord < ActiveRecord::Base
|
||||
include Events::Types
|
||||
self.abstract_class = true
|
||||
|
||||
before_validation :validates_column_content_length
|
||||
|
||||
# the models that exposed in email templates through liquid
|
||||
DROPPABLES = %w[Account Channel Conversation Inbox User Message].freeze
|
||||
|
||||
@@ -14,6 +16,31 @@ class ApplicationRecord < ActiveRecord::Base
|
||||
|
||||
private
|
||||
|
||||
# Generic validation for all columns of type string and text
|
||||
# Validates the length of the column to prevent DOS via large payloads
|
||||
# if a custom length validation is already present, skip the validation
|
||||
def validates_column_content_length
|
||||
self.class.columns.each do |column|
|
||||
check_and_validate_content_length(column) if column_of_type_string_or_text?(column)
|
||||
end
|
||||
end
|
||||
|
||||
def column_of_type_string_or_text?(column)
|
||||
%i[string text].include?(column.type)
|
||||
end
|
||||
|
||||
def check_and_validate_content_length(column)
|
||||
length_validator = self.class.validators_on(column.name).find { |v| v.kind == :length }
|
||||
validate_content_length(column) if length_validator.blank?
|
||||
end
|
||||
|
||||
def validate_content_length(column)
|
||||
max_length = column.type == :text ? 20_000 : 255
|
||||
return if self[column.name].nil? || self[column.name].length <= max_length
|
||||
|
||||
errors.add(column.name.to_sym, "is too long (maximum is #{max_length} characters)")
|
||||
end
|
||||
|
||||
def normalize_empty_string_to_nil(attrs = [])
|
||||
attrs.each do |attr|
|
||||
self[attr] = nil if self[attr].blank?
|
||||
|
||||
@@ -36,7 +36,6 @@ class Contact < ApplicationRecord
|
||||
validates :phone_number,
|
||||
allow_blank: true, uniqueness: { scope: [:account_id] },
|
||||
format: { with: /\+[1-9]\d{1,14}\z/, message: I18n.t('errors.contacts.phone_number.invalid') }
|
||||
validates :name, length: { maximum: 255 }
|
||||
|
||||
belongs_to :account
|
||||
has_many :conversations, dependent: :destroy_async
|
||||
|
||||
Reference in New Issue
Block a user