scout_apm 6.4.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 946b50c247963854bd791e98c90767ad678d809c4381df93d8e8cde5bec5d588
4
- data.tar.gz: 6151cbb3f58f099a72e7c641f3a61e88071cd63bdb414a4043274abec7a66f70
3
+ metadata.gz: dcd4cff0ac055288f03c80d5278f193a776fc12f3e5c133bc6e6ef5beccdd54d
4
+ data.tar.gz: a4247f5c49c33c59ed73e111c8c4b6508e080f0ea789fe9c476378b8335df05c
5
5
  SHA512:
6
- metadata.gz: 06fa78cd3cebbce4494a2c3f08baf070e643014d6b6499bb6a1504a49fc3366574afc0a0c08f8d7f0374c1d8174b4cc783d0c32669bf8fe028eeb8213efb75bd
7
- data.tar.gz: 31e85d68da2919b8db05b705a64594ce4d112185ad664556e86268f358bbd0dcb6cd6b441598a542a31fbe6d9a3bf6afdb33666c1fba8d5c97970980fb18f737
6
+ metadata.gz: f64b1a132f0fa5dc7d3dfab68fb54612e83a9ad9fc9779dd78000a37609e6ed8106df4ee841a636cf2296c683ecc77244cb9a7194060e2782394164db2d89e46
7
+ data.tar.gz: '09d21137389a2dd60f37b93c3befeb6dfa79acdbfd3cef9510eb045407f461af63c28d086f1bd8a3f560761a419207134c58004d646c255f4b0f3e04018b1e20'
data/CHANGELOG.markdown CHANGED
@@ -1,5 +1,14 @@
1
1
  # Pending
2
2
 
3
+ # 7.0.0
4
+
5
+ This release officially drops support for Ruby 2.1 through 2.4. The gem now requires Ruby 2.5 or newer.
6
+
7
+ - Require Ruby 2.5 or newer (`required_ruby_version >= 2.5`); Ruby 2.1–2.4 are no longer supported
8
+ - Avoid Ruby 3.4+ "literal string will be frozen" deprecation warnings in `UniqueId` and `LayawayFile` (#652)
9
+ - DevTrace now injects its trace into HTML responses that another middleware, such as Hotwire::Spark, returns as a plain Array body (#653)
10
+ - Resque: forked workers now send the parent's remote server a token it generates at startup, and a second Resque parent on the same host binds a free port if `remote_agent_port` is taken (#654)
11
+
3
12
  # 6.4.0
4
13
 
5
14
  HTTPS reporting now verifies Scout's certificates against the OS trust store by default instead of the CA file bundled with the gem. To keep using a specific CA file, set `SCOUT_SSL_CERT_FILE` (or `ssl_cert_file`) to its path.
@@ -37,29 +37,49 @@ module ScoutApm
37
37
  #####################################
38
38
 
39
39
  def start_remote_server!(bind, port)
40
- return if @remote_server && @remote_server.running?
40
+ return if @remote_server && @remote_server.started?
41
41
 
42
42
  logger.info("Starting Remote Agent Server")
43
43
 
44
- # Start the listening web server only in parent process.
45
- @remote_server = ScoutApm::Remote::Server.new(
46
- bind,
47
- port,
48
- ScoutApm::Remote::Router.new(ScoutApm::SynchronousRecorder.new(self), logger),
49
- logger
50
- )
44
+ # Generated before forking, so every child inherits it and the server
45
+ # only accepts messages from its own children.
46
+ @remote_token ||= SecureRandom.hex(32)
51
47
 
52
- @remote_server.start
48
+ # Start the listening web server only in parent process.
49
+ begin
50
+ @remote_server = build_remote_server(bind, port)
51
+ @remote_server.start
52
+ rescue Errno::EADDRINUSE
53
+ # Another process (e.g. a second Resque parent on this host) has the
54
+ # port. Bind a free port instead; children inherit it below.
55
+ logger.info("Remote Agent Server: port #{port} is in use, binding a free port instead")
56
+ @remote_server = build_remote_server(bind, 0)
57
+ @remote_server.start
58
+ end
53
59
  end
54
60
 
55
61
  # Execute this in the child process of a remote agent. The parent is
56
62
  # expected to have its accepting webserver up and running
57
63
  def become_remote_client!(host, port)
64
+ # Use the port the parent actually bound, which differs from the
65
+ # configured one if that was in use.
66
+ port = @remote_server.port if @remote_server && @remote_server.port
58
67
  logger.debug("Becoming Remote Agent (reporting to: #{host}:#{port})")
59
- @recorder = ScoutApm::Remote::Recorder.new(host, port, logger)
68
+ @recorder = ScoutApm::Remote::Recorder.new(host, port, logger, @remote_token)
60
69
  @store = ScoutApm::FakeStore.new
61
70
  end
62
71
 
72
+ def build_remote_server(bind, port)
73
+ ScoutApm::Remote::Server.new(
74
+ bind,
75
+ port,
76
+ ScoutApm::Remote::Router.new(ScoutApm::SynchronousRecorder.new(self), logger),
77
+ logger,
78
+ @remote_token
79
+ )
80
+ end
81
+ private :build_remote_server
82
+
63
83
 
64
84
  ###############
65
85
  # Accessors #
@@ -138,6 +138,7 @@ module ScoutApm
138
138
  case true
139
139
  when older_rails_response? then adjust_older_rails_response
140
140
  when newer_rails_response? then adjust_newer_rails_response
141
+ when html_array_response? then adjust_html_array_response
141
142
  when rack_proxy_response? then adjust_rack_proxy_response
142
143
  else
143
144
  # No action taken, we only adjust if we know exactly what we have.
@@ -160,6 +161,12 @@ module ScoutApm
160
161
  rack_body.is_a?(::Rack::BodyProxy)
161
162
  end
162
163
 
164
+ # Some middleware (for example Hotwire::Spark) read the app's response
165
+ # body, rewrite the HTML and hand back a plain Array of strings.
166
+ def html_array_response?
167
+ rack_body.is_a?(Array) && content_type.to_s.include?("text/html")
168
+ end
169
+
163
170
  def adjust_older_rails_response
164
171
  logger.debug("DevTrace: in middleware, dev_trace is active, and response has a (older) body. This appears to be an HTML page and an ActionDispatch::Response. Path=#{path}; ContentType=#{content_type}")
165
172
  rack_body.body = [ html_manipulator.res ]
@@ -177,10 +184,21 @@ module ScoutApm
177
184
  @rack_headers.delete("Content-Length")
178
185
  end
179
186
 
187
+ def adjust_html_array_response
188
+ logger.debug("DevTrace: in middleware, dev_trace is active, and response has a body. This appears to be an HTML page in an Array body. Path=#{path}; ContentType=#{content_type}")
189
+ @rack_body = [ html_manipulator.res ]
190
+ delete_content_length
191
+ end
192
+
193
+ def delete_content_length
194
+ @rack_headers.delete("Content-Length")
195
+ @rack_headers.delete("content-length")
196
+ end
197
+
180
198
  def html_manipulator
181
199
  @html_manipulator ||=
182
200
  begin
183
- page = ScoutApm::Instant::Page.new(rack_body.body)
201
+ page = ScoutApm::Instant::Page.new(html_array_response? ? rack_body : rack_body.body)
184
202
 
185
203
  # This monkey-patches XMLHttpRequest. It could possibly be part of the main scout_instant.js too. Putting it here so it runs as soon as possible.
186
204
  page.add_to_head(ScoutApm::Instant::Util.read_asset("xmlhttp_instrumentation.html"))
@@ -199,7 +217,7 @@ module ScoutApm
199
217
  end
200
218
 
201
219
  def development_asset?
202
- !rack_body.respond_to?(:body)
220
+ !rack_body.respond_to?(:body) && !html_array_response?
203
221
  end
204
222
 
205
223
  def path
@@ -207,7 +225,7 @@ module ScoutApm
207
225
  end
208
226
 
209
227
  def content_type
210
- rack_headers['Content-Type']
228
+ rack_headers['Content-Type'] || rack_headers['content-type']
211
229
  end
212
230
 
213
231
  ##############################
@@ -41,7 +41,7 @@ module ScoutApm
41
41
  end
42
42
 
43
43
  def read_raw(f)
44
- contents = ""
44
+ contents = +""
45
45
  while true
46
46
  contents << f.read_nonblock(10_000)
47
47
  end
@@ -1,5 +1,19 @@
1
1
  module ScoutApm
2
2
  module Remote
3
+ # Header the forked children send with every message. The value is a token
4
+ # the parent generates before forking, so the children inherit it.
5
+ TOKEN_HEADER = "X-Scout-Remote-Token".freeze
6
+
7
+ # Constant-time string comparison, so response timing doesn't reveal how
8
+ # much of the token matched.
9
+ def self.secure_compare(a, b)
10
+ return false unless a.bytesize == b.bytesize
11
+
12
+ result = 0
13
+ a.bytes.zip(b.bytes) { |x, y| result |= x ^ y }
14
+ result == 0
15
+ end
16
+
3
17
  class Message
4
18
  attr_reader :type
5
19
  attr_reader :command
@@ -5,10 +5,11 @@ module ScoutApm
5
5
  attr_reader :remote_agent_host
6
6
  attr_reader :remote_agent_port
7
7
 
8
- def initialize(remote_agent_host, remote_agent_port, logger)
8
+ def initialize(remote_agent_host, remote_agent_port, logger, token)
9
9
  @remote_agent_host = remote_agent_host
10
10
  @remote_agent_port = remote_agent_port
11
11
  @logger = logger
12
+ @token = token
12
13
  end
13
14
 
14
15
  def start
@@ -49,8 +50,13 @@ module ScoutApm
49
50
  def post(encoded_message)
50
51
  http = Net::HTTP.new(remote_agent_host, remote_agent_port)
51
52
  request = Net::HTTP::Post.new("/users")
53
+ request[ScoutApm::Remote::TOKEN_HEADER] = @token.to_s
52
54
  request.body = encoded_message
53
55
  response = http.request(request)
56
+ unless response.is_a?(Net::HTTPSuccess)
57
+ logger.debug "Remote: Server did not accept message: #{response.code}"
58
+ end
59
+ response
54
60
  end
55
61
  end
56
62
  end
@@ -4,6 +4,12 @@ module ScoutApm
4
4
  attr_reader :logger
5
5
  attr_reader :routes
6
6
 
7
+ # The only commands each route accepts. Keys are types, values are
8
+ # command names.
9
+ ALLOWED_COMMANDS = {
10
+ 'record' => ['record!'].freeze,
11
+ }.freeze
12
+
7
13
  # If/When we add different types, this signature should change to a hash
8
14
  # of {type => Object}, rather than building it in the initializer here.
9
15
  #
@@ -21,7 +27,7 @@ module ScoutApm
21
27
  #
22
28
  # Where
23
29
  # type: ['recorder']
24
- # command: any function supported on that type of object
30
+ # command: one of ALLOWED_COMMANDS for that type
25
31
  # args: any array of arguments
26
32
  #
27
33
  # Raises on unknown message
@@ -39,10 +45,14 @@ module ScoutApm
39
45
  if ! routes.keys.include?(message.type.to_s)
40
46
  raise "Unknown type: #{message.type.to_s}"
41
47
  end
48
+
49
+ if ! ALLOWED_COMMANDS.fetch(message.type.to_s, []).include?(message.command.to_s)
50
+ raise "Unknown command: #{message.command.to_s}"
51
+ end
42
52
  end
43
53
 
44
54
  def call_route(message)
45
- routes[message.type].send(message.command, *message.args)
55
+ routes[message.type.to_s].public_send(message.command.to_s, *message.args)
46
56
  end
47
57
  end
48
58
  end
@@ -8,11 +8,12 @@ module ScoutApm
8
8
  attr_reader :port
9
9
  attr_reader :logger
10
10
 
11
- def initialize(bind, port, router, logger)
11
+ def initialize(bind, port, router, logger, token)
12
12
  @router = router
13
13
  @logger = logger
14
14
  @bind = bind
15
15
  @port = port
16
+ @token = token
16
17
  @server = nil
17
18
  end
18
19
 
@@ -37,12 +38,20 @@ module ScoutApm
37
38
  :AccessLog => [],
38
39
  :Logger => @logger
39
40
  )
41
+ # When asked for port 0, WEBrick binds a free port and records it here.
42
+ @port = @server.config[:Port]
40
43
 
41
44
  @server.mount_proc '/' do |request, response|
42
- router.handle(request.body)
45
+ if authorized?(request)
46
+ router.handle(request.body)
43
47
 
44
- # arbitrary response, client doesn't expect anything in particular
45
- response.body = 'Ok'
48
+ # arbitrary response, client doesn't expect anything in particular
49
+ response.body = 'Ok'
50
+ else
51
+ logger.debug("Remote: Rejected a message without a valid #{TOKEN_HEADER} header")
52
+ response.status = 403
53
+ response.body = 'Forbidden'
54
+ end
46
55
  end
47
56
 
48
57
  @thread = Thread.new do
@@ -58,6 +67,19 @@ module ScoutApm
58
67
  end
59
68
  end
60
69
 
70
+ # Only accept messages from our own forked children, which inherit the
71
+ # token from the parent process.
72
+ def authorized?(request)
73
+ given = request[TOKEN_HEADER].to_s
74
+ !@token.to_s.empty? && Remote.secure_compare(given, @token)
75
+ end
76
+
77
+ # True from the moment the listening socket is bound until #stop, unlike
78
+ # #running?, which waits for the server thread to start.
79
+ def started?
80
+ !!@server && @server.status != :Shutdown
81
+ end
82
+
61
83
  def running?
62
84
  @thread.alive?
63
85
  @server && @server.status == :Running
@@ -4,7 +4,7 @@ module ScoutApm
4
4
  ALPHABET = ('a'..'z').to_a.freeze
5
5
 
6
6
  def self.simple(length=16)
7
- s = ""
7
+ s = +""
8
8
  length.times do
9
9
  s << ALPHABET[rand(26)]
10
10
  end
@@ -1,3 +1,3 @@
1
1
  module ScoutApm
2
- VERSION = "6.4.0"
2
+ VERSION = "7.0.0"
3
3
  end
data/scout_apm.gemspec CHANGED
@@ -25,7 +25,7 @@ Gem::Specification.new do |s|
25
25
  s.extensions << 'ext/allocations/extconf.rb'
26
26
  s.extensions << 'ext/rusage/extconf.rb'
27
27
 
28
- s.required_ruby_version = '>= 2.1'
28
+ s.required_ruby_version = '>= 2.5'
29
29
 
30
30
 
31
31
  s.add_development_dependency "minitest"
data/test/test_helper.rb CHANGED
@@ -26,6 +26,17 @@ Kernel.module_eval do
26
26
  $VERBOSE = warn_level
27
27
  result
28
28
  end
29
+
30
+ # Returns any deprecation warnings (eg. mutating a string literal on Ruby 3.4+) emitted by the block.
31
+ def capture_deprecation_warnings(&block)
32
+ return "" unless Warning.respond_to?(:[]=)
33
+ deprecated = Warning[:deprecated]
34
+ Warning[:deprecated] = true
35
+ _out, err = capture_io(&block)
36
+ err
37
+ ensure
38
+ Warning[:deprecated] = deprecated if Warning.respond_to?(:[]=)
39
+ end
29
40
  end
30
41
 
31
42
  # A test helper class to create a temporary "configuration" we can control entirely purposes
@@ -35,4 +35,42 @@ class AgentContextTest < Minitest::Test
35
35
  context.slow_request_policy.add(TestPolicy.new)
36
36
  assert 5, context.slow_request_policy.policies
37
37
  end
38
+
39
+ def test_remote_client_uses_parent_token_and_port
40
+ context = ScoutApm::AgentContext.new
41
+ server = stub(:start => true, :port => 54321)
42
+ ScoutApm::Remote::Server.expects(:new).with { |_bind, port, _router, _logger, token|
43
+ port == 7721 && token.is_a?(String) && token.length == 64
44
+ }.returns(server)
45
+
46
+ context.start_remote_server!("127.0.0.1", 7721)
47
+ token = context.instance_variable_get(:@remote_token)
48
+
49
+ ScoutApm::Remote::Recorder.expects(:new).with("127.0.0.1", 54321, anything, token)
50
+ context.become_remote_client!("127.0.0.1", 7721)
51
+ end
52
+
53
+ def test_remote_server_binds_a_free_port_when_configured_port_is_in_use
54
+ context = ScoutApm::AgentContext.new
55
+ busy = stub(:port => 7721)
56
+ busy.stubs(:start).raises(Errno::EADDRINUSE)
57
+ free = stub(:start => true, :port => 54321)
58
+
59
+ ScoutApm::Remote::Server.expects(:new).with { |_b, port, *| port == 7721 }.returns(busy)
60
+ ScoutApm::Remote::Server.expects(:new).with { |_b, port, *| port == 0 }.returns(free)
61
+
62
+ context.start_remote_server!("127.0.0.1", 7721)
63
+
64
+ ScoutApm::Remote::Recorder.expects(:new).with("127.0.0.1", 54321, anything, anything)
65
+ context.become_remote_client!("127.0.0.1", 7721)
66
+ end
67
+
68
+ def test_remote_server_is_only_started_once
69
+ context = ScoutApm::AgentContext.new
70
+ server = stub(:start => true, :port => 7721, :started? => true)
71
+ ScoutApm::Remote::Server.expects(:new).once.returns(server)
72
+
73
+ context.start_remote_server!("127.0.0.1", 7721)
74
+ context.start_remote_server!("127.0.0.1", 7721)
75
+ end
38
76
  end
@@ -0,0 +1,52 @@
1
+ require 'test_helper'
2
+
3
+ require 'scout_apm/instant/middleware'
4
+
5
+ class InstantMiddlewareTest < Minitest::Test
6
+ HTML = "<html><head></head><body><p>hi</p></body></html>".freeze
7
+
8
+ def setup
9
+ ScoutApm::Instant::DevTraceResponseManipulator.any_instance.stubs(:dev_trace_disabled?).returns(false)
10
+ ScoutApm::Instant::DevTraceResponseManipulator.any_instance.stubs(:tracked_request).returns(stub(:ignoring_request? => false))
11
+ ScoutApm::Instant::DevTraceResponseManipulator.any_instance.stubs(:trace).returns(Object.new)
12
+ ScoutApm::Instant::DevTraceResponseManipulator.any_instance.stubs(:payload).returns("{}")
13
+ end
14
+
15
+ # Hotwire::Spark rewrites the HTML and returns a plain Array body.
16
+ def test_injects_dev_trace_into_html_array_body
17
+ headers = { "Content-Type" => "text/html; charset=utf-8", "Content-Length" => HTML.bytesize.to_s }
18
+ status, new_headers, body = manipulate([200, headers, [HTML.dup]])
19
+
20
+ assert_equal 200, status
21
+ assert_includes body.join, "scout_instant.js"
22
+ assert_includes body.join, "scoutInstantPageTrace"
23
+ refute new_headers.key?("Content-Length")
24
+ end
25
+
26
+ def test_handles_lowercase_rack3_headers
27
+ headers = { "content-type" => "text/html", "content-length" => HTML.bytesize.to_s }
28
+ _status, new_headers, body = manipulate([200, headers, [HTML.dup]])
29
+
30
+ assert_includes body.join, "scout_instant.js"
31
+ refute new_headers.key?("content-length")
32
+ end
33
+
34
+ def test_leaves_non_html_array_body_alone
35
+ response = [200, { "Content-Type" => "text/css" }, ["body { color: red }"]]
36
+ assert_equal response, manipulate(response)
37
+ end
38
+
39
+ def test_leaves_file_body_alone
40
+ file_body = Object.new
41
+ def file_body.each; yield "x"; end
42
+ response = [200, { "Content-Type" => "text/html" }, file_body]
43
+ assert_same file_body, manipulate(response)[2]
44
+ end
45
+
46
+ private
47
+
48
+ def manipulate(response)
49
+ env = { "PATH_INFO" => "/" }
50
+ ScoutApm::Instant::DevTraceResponseManipulator.new(env, response).call
51
+ end
52
+ end
@@ -0,0 +1,23 @@
1
+ require 'test_helper'
2
+ require 'scout_apm/layaway_file'
3
+
4
+ require 'tmpdir'
5
+ class LayawayFileTest < Minitest::Test
6
+ def test_write_and_load
7
+ Dir.mktmpdir do |dir|
8
+ file = ScoutApm::LayawayFile.new(ScoutApm::AgentContext.new, File.join(dir, "layaway"))
9
+ file.write({ "foo" => [1, 2, 3] })
10
+
11
+ assert_equal({ "foo" => [1, 2, 3] }, file.load)
12
+ end
13
+ end
14
+
15
+ def test_load_does_not_mutate_string_literal
16
+ Dir.mktmpdir do |dir|
17
+ file = ScoutApm::LayawayFile.new(ScoutApm::AgentContext.new, File.join(dir, "layaway"))
18
+ file.write({ "foo" => "bar" })
19
+
20
+ assert_equal "", capture_deprecation_warnings { file.load }
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,15 @@
1
+ require 'test_helper'
2
+
3
+ class RemoteRecorderTest < Minitest::Test
4
+ def test_post_sends_token_header
5
+ recorder = ScoutApm::Remote::Recorder.new("127.0.0.1", 7721, Logger.new(StringIO.new), "the-token")
6
+
7
+ http = mock
8
+ Net::HTTP.expects(:new).with("127.0.0.1", 7721).returns(http)
9
+ http.expects(:request).with { |req|
10
+ req[ScoutApm::Remote::TOKEN_HEADER] == "the-token" && req.body == "payload"
11
+ }.returns(Net::HTTPOK.new("1.1", "200", "OK"))
12
+
13
+ recorder.post("payload")
14
+ end
15
+ end
@@ -4,9 +4,9 @@ class RouterTest < Minitest::Test
4
4
  def test_router_handles_record
5
5
  recorder = stub
6
6
  router = ScoutApm::Remote::Router.new(recorder, logger)
7
- message = ScoutApm::Remote::Message.new("record", "foo", 1, 2).encode
7
+ message = ScoutApm::Remote::Message.new("record", "record!", 1).encode
8
8
 
9
- recorder.expects(:foo).with(1, 2)
9
+ recorder.expects(:record!).with(1)
10
10
 
11
11
  router.handle(message)
12
12
  end
@@ -14,12 +14,33 @@ class RouterTest < Minitest::Test
14
14
  def test_router_raises_on_unknown_types
15
15
  recorder = stub
16
16
  router = ScoutApm::Remote::Router.new(recorder, logger)
17
- message = ScoutApm::Remote::Message.new("something_else", "foo", 1, 2).encode
17
+ message = ScoutApm::Remote::Message.new("something_else", "record!", 1).encode
18
+
19
+ recorder.expects(:record!).never
20
+ assert_raises do
21
+ router.handle(message)
22
+ end
23
+ end
24
+
25
+ def test_router_raises_on_unknown_commands
26
+ recorder = stub
27
+ router = ScoutApm::Remote::Router.new(recorder, logger)
18
28
 
19
29
  recorder.expects(:foo).never
30
+ assert_raises do
31
+ router.handle(ScoutApm::Remote::Message.new("record", "foo", 1, 2).encode)
32
+ end
33
+ end
34
+
35
+ def test_router_only_calls_allowed_commands
36
+ recorder = Object.new
37
+ router = ScoutApm::Remote::Router.new(recorder, logger)
38
+ message = ScoutApm::Remote::Message.new("record", "instance_eval", "@called = true").encode
39
+
20
40
  assert_raises do
21
41
  router.handle(message)
22
42
  end
43
+ assert_nil recorder.instance_variable_get(:@called)
23
44
  end
24
45
 
25
46
  def logger
@@ -30,4 +51,3 @@ class RouterTest < Minitest::Test
30
51
  @logger_io ||= StringIO.new
31
52
  end
32
53
  end
33
-
@@ -0,0 +1,16 @@
1
+ require 'test_helper'
2
+
3
+ class RemoteSecureCompareTest < Minitest::Test
4
+ def test_equal_strings
5
+ assert ScoutApm::Remote.secure_compare("abc123", "abc123")
6
+ end
7
+
8
+ def test_different_strings_of_same_length
9
+ refute ScoutApm::Remote.secure_compare("abc123", "abc124")
10
+ end
11
+
12
+ def test_different_lengths
13
+ refute ScoutApm::Remote.secure_compare("abc", "abc123")
14
+ refute ScoutApm::Remote.secure_compare("", "abc")
15
+ end
16
+ end
@@ -1,18 +1,86 @@
1
1
  require 'test_helper'
2
+ require 'socket'
2
3
 
3
4
  class TestRemoteServer < Minitest::Test
4
- def test_start_and_bind
5
- bind = "127.0.0.1"
6
- port = 8938
7
- router = stub(:router)
8
- logger_io = StringIO.new
9
- server = ScoutApm::Remote::Server.new(bind, port, router, Logger.new(logger_io))
5
+ TOKEN = "a" * 64
6
+
7
+ def setup
8
+ @router = stub(:router)
9
+ @server = ScoutApm::Remote::Server.new("127.0.0.1", 0, @router, Logger.new(StringIO.new), TOKEN)
10
10
 
11
11
  # Cannot test this if we can't require webrick. Ruby 3 stopped including by default
12
- skip unless server.require_webrick
12
+ skip unless @server.require_webrick
13
+ end
14
+
15
+ def teardown
16
+ @server.stop if @server && @server.running?
17
+ end
18
+
19
+ def test_start_and_bind
20
+ start_server
21
+ assert @server.running?
22
+ end
23
+
24
+ def test_started_as_soon_as_start_returns
25
+ refute @server.started?
26
+ @server.start
27
+ assert @server.started?
28
+ end
29
+
30
+ def test_binds_a_free_port_when_given_port_zero
31
+ start_server
32
+ assert_operator @server.port, :>, 0
33
+ end
34
+
35
+ def test_accepts_message_with_valid_token
36
+ @router.expects(:handle).with("payload").once
37
+ start_server
38
+
39
+ response = post("payload", TOKEN)
40
+ assert_equal "200", response.code
41
+ end
42
+
43
+ def test_rejects_message_without_token
44
+ @router.expects(:handle).never
45
+ start_server
46
+
47
+ response = post("payload", nil)
48
+ assert_equal "403", response.code
49
+ end
50
+
51
+ def test_rejects_message_with_wrong_token
52
+ @router.expects(:handle).never
53
+ start_server
54
+
55
+ response = post("payload", "b" * 64)
56
+ assert_equal "403", response.code
57
+ end
58
+
59
+ def test_rejects_everything_when_server_has_no_token
60
+ @router.expects(:handle).never
61
+ @server = ScoutApm::Remote::Server.new("127.0.0.1", 0, @router, Logger.new(StringIO.new), nil)
62
+ start_server
63
+
64
+ assert_equal "403", post("payload", "").code
65
+ end
66
+
67
+ private
68
+
69
+ def start_server
70
+ @server.start
71
+ sleep 0.05 # Let the server finish starting
72
+ end
73
+
74
+ Response = Struct.new(:code)
13
75
 
14
- server.start
15
- sleep 0.05 # Let the server finish starting. The assert should instead allow a time
16
- assert server.running?
76
+ # Raw HTTP over a socket, since other tests may leave Net::HTTP instrumented.
77
+ def post(body, token)
78
+ headers = ["POST /users HTTP/1.1", "Host: 127.0.0.1", "Content-Length: #{body.bytesize}", "Connection: close"]
79
+ headers << "#{ScoutApm::Remote::TOKEN_HEADER}: #{token}" if token
80
+ socket = TCPSocket.new("127.0.0.1", @server.port)
81
+ socket.write(headers.join("\r\n") + "\r\n\r\n" + body)
82
+ Response.new(socket.read[/\AHTTP\/1\.\d (\d{3})/, 1])
83
+ ensure
84
+ socket.close if socket
17
85
  end
18
86
  end
@@ -0,0 +1,16 @@
1
+ require 'test_helper'
2
+ require 'scout_apm/utils/unique_id'
3
+
4
+ class UniqueIdTest < Minitest::Test
5
+ UniqueId = ScoutApm::Utils::UniqueId
6
+
7
+ def test_simple
8
+ id = UniqueId.simple
9
+ assert_match(/\A[a-z]{16}\z/, id)
10
+ assert_match(/\A[a-z]{4}\z/, UniqueId.simple(4))
11
+ end
12
+
13
+ def test_simple_does_not_mutate_string_literal
14
+ assert_equal "", capture_deprecation_warnings { UniqueId.simple }
15
+ end
16
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: scout_apm
3
3
  version: !ruby/object:Gem::Version
4
- version: 6.4.0
4
+ version: 7.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Derek Haynes
@@ -461,6 +461,7 @@ files:
461
461
  - test/unit/git_revision_test.rb
462
462
  - test/unit/histogram_test.rb
463
463
  - test/unit/ignored_uris_test.rb
464
+ - test/unit/instant/middleware_test.rb
464
465
  - test/unit/instruments/action_view_test.rb
465
466
  - test/unit/instruments/active_record_test.rb
466
467
  - test/unit/instruments/fixtures/test/_test_partial.html.erb
@@ -475,6 +476,7 @@ files:
475
476
  - test/unit/instruments/percentile_sampler_test.rb
476
477
  - test/unit/instruments/redis_test.rb
477
478
  - test/unit/instruments/typhoeus_test.rb
479
+ - test/unit/layaway_file_test.rb
478
480
  - test/unit/layaway_test.rb
479
481
  - test/unit/layer_children_set_test.rb
480
482
  - test/unit/layer_converters/depth_first_walker_test.rb
@@ -484,7 +486,9 @@ files:
484
486
  - test/unit/logger_test.rb
485
487
  - test/unit/metric_set_test.rb
486
488
  - test/unit/remote/message_test.rb
489
+ - test/unit/remote/recorder_test.rb
487
490
  - test/unit/remote/route_test.rb
491
+ - test/unit/remote/secure_compare_test.rb
488
492
  - test/unit/remote/server_test.rb
489
493
  - test/unit/reporter_test.rb
490
494
  - test/unit/reporting_test.rb
@@ -504,6 +508,7 @@ files:
504
508
  - test/unit/utils/backtrace_parser_test.rb
505
509
  - test/unit/utils/numbers_test.rb
506
510
  - test/unit/utils/scm.rb
511
+ - test/unit/utils/unique_id_test.rb
507
512
  homepage: https://github.com/scoutapp/scout_apm_ruby
508
513
  licenses:
509
514
  - MIT
@@ -519,7 +524,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
519
524
  requirements:
520
525
  - - ">="
521
526
  - !ruby/object:Gem::Version
522
- version: '2.1'
527
+ version: '2.5'
523
528
  required_rubygems_version: !ruby/object:Gem::Requirement
524
529
  requirements:
525
530
  - - ">="