Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion lib/stripe/api_requestor.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# frozen_string_literal: true

require "digest"
require "socket"
require "stripe/instrumentation"

module Stripe
Expand Down Expand Up @@ -1066,6 +1068,31 @@ def dup_from_response_headers(headers)
# in so that we can generate a rich user agent header to help debug
# integrations.
class SystemProfiler
UNAME_HASH = begin
parts = []
parts << if RUBY_PLATFORM.match?(/mswin|mingw|cygwin/)
begin
`ver 2>NUL`.strip
rescue StandardError
""
end
else
begin
`uname -a 2>/dev/null`.strip
rescue StandardError
""
end
end
parts << begin
Socket.gethostname
rescue StandardError
""
end
Digest::MD5.hexdigest(parts.join(" "))
rescue StandardError
""
end

AI_AGENTS = [
# aiAgents: The beginning of the section generated from our OpenAPI spec
%w[ANTIGRAVITY_CLI_ALIAS antigravity],
Expand Down Expand Up @@ -1101,7 +1128,10 @@ def self.user_agent
engine: defined?(RUBY_ENGINE) ? RUBY_ENGINE : "",
}.delete_if { |_k, v| v.nil? }

ua[:platform] = RUBY_PLATFORM if Stripe.enable_telemetry?
if Stripe.enable_telemetry?
ua[:platform] = RUBY_PLATFORM
ua[:source] = UNAME_HASH unless UNAME_HASH.empty?
end

ai_agent = detect_ai_agent
ua[:ai_agent] = ai_agent unless ai_agent.empty?
Expand Down
26 changes: 26 additions & 0 deletions test/stripe/api_requestor_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1799,6 +1799,32 @@ class SystemProfilerTest < Test::Unit::TestCase
ensure
Stripe.enable_telemetry = false
end

should "omit source when UNAME_HASH is empty" do
original = APIRequestor::SystemProfiler::UNAME_HASH
APIRequestor::SystemProfiler.send(:remove_const, :UNAME_HASH)
APIRequestor::SystemProfiler.const_set(:UNAME_HASH, "")
Stripe.enable_telemetry = true
ua = APIRequestor::SystemProfiler.user_agent
refute ua.key?(:source)
ensure
APIRequestor::SystemProfiler.send(:remove_const, :UNAME_HASH)
APIRequestor::SystemProfiler.const_set(:UNAME_HASH, original)
Stripe.enable_telemetry = false
end

should "include source when UNAME_HASH is non-empty" do
original = APIRequestor::SystemProfiler::UNAME_HASH
APIRequestor::SystemProfiler.send(:remove_const, :UNAME_HASH)
APIRequestor::SystemProfiler.const_set(:UNAME_HASH, "abc123")
Stripe.enable_telemetry = true
ua = APIRequestor::SystemProfiler.user_agent
assert_equal "abc123", ua[:source]
ensure
APIRequestor::SystemProfiler.send(:remove_const, :UNAME_HASH)
APIRequestor::SystemProfiler.const_set(:UNAME_HASH, original)
Stripe.enable_telemetry = false
end
end

context ".detect_ai_agent" do
Expand Down
Loading