DEV: Truncate user agent string when it is too long instead of null (#27758)

This is a follow up to 005f623c42 where
we want to truncate the user agent string instead of nulling out the
column when the user agent string is too low. By truncating, we still
get to retain information that can still be useful.
This commit is contained in:
Alan Guo Xiang Tan 2024-07-08 13:58:20 +08:00 committed by GitHub
parent f9a5d149e1
commit c3598847fe
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 19 additions and 14 deletions

View File

@ -1,7 +1,10 @@
# frozen_string_literal: true
class 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::Base
ip_address = nil if user_id
key = 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: "")
end
result = nil

View File

@ -7,30 +7,30 @@ RSpec.describe SearchLog, type: :model do
context "with invalid arguments" do
it "no search type returns error" do
status, _ =
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)
end
it "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)
end
end