A platform for community discussion. Free, open, simple.
DEV: Truncate user agent string when it is too long instead of null (#27758)
Alan Guo Xiang Tanc3598847fe47
diff --git a/app/models/search_log.rb b/app/models/search_log.rbindex 0cbbdee8d18..b134dc04cdf 100644--- a/app/models/search_log.rb+++ b/app/models/search_log.rb@@ -1,7 +1,10 @@# frozen_string_literal: trueclass SearchLog < ActiveRecord::Base+ MAXIMUM_USER_AGENT_LENGTH = 2000+validates_presence_of :term+ validates :user_agent, length: { maximum: MAXIMUM_USER_AGENT_LENGTH }belongs_to :user@@ -41,7 +44,9 @@ class SearchLog < ActiveRecord::Baseip_address = nil if user_idkey = redis_key(user_id: user_id, ip_address: ip_address)- user_agent = nil if user_agent && user_agent.length > 2000+ if user_agent && user_agent.length > MAXIMUM_USER_AGENT_LENGTH+ user_agent = user_agent.truncate(MAXIMUM_USER_AGENT_LENGTH, omission: "")+ endresult = nildiff --git a/spec/models/search_log_spec.rb b/spec/models/search_log_spec.rbindex 98f00bbb829..de5c8967f02 100644--- a/spec/models/search_log_spec.rb+++ b/spec/models/search_log_spec.rb@@ -7,30 +7,30 @@ RSpec.describe SearchLog, type: :model docontext "with invalid arguments" doit "no search type returns error" dostatus, _ =- SearchLog.log(- term: "bounty hunter",- search_type: :missing,- ip_address: "127.0.0.1",- user_agent: "Mozilla",- )+ SearchLog.log(term: "bounty hunter", search_type: :missing, ip_address: "127.0.0.1")+expect(status).to eq(:error)endit "no IP returns error" do+ status, _ = SearchLog.log(term: "bounty hunter", search_type: :header, ip_address: nil)++ expect(status).to eq(:error)+ end++ it "truncates the `user_agent` attribute if it exceeds #{described_class::MAXIMUM_USER_AGENT_LENGTH} characters" do+ user_agent = "a" * (described_class::MAXIMUM_USER_AGENT_LENGTH + 1)+status, _ =SearchLog.log(term: "bounty hunter",search_type: :header,- ip_address: nil,- user_agent: "Mozilla",+ user_agent:,+ ip_address: "127.0.0.1",)- expect(status).to eq(:error)- end- it "does not error when no user_agent" do- status, _ =- SearchLog.log(term: "bounty hunter", search_type: :header, ip_address: "127.0.0.1")expect(status).to eq(:created)+ expect(SearchLog.last.user_agent).to eq("a" * described_class::MAXIMUM_USER_AGENT_LENGTH)endend