sentrace 0.1.2 → 0.1.3

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.
Files changed (32) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +10 -0
  3. data/app/assets/javascripts/sentrace.browser.js +101 -28
  4. data/app/assets/javascripts/sentrace.js +101 -28
  5. data/app/controllers/sentrace/application_controller.rb +4 -4
  6. data/app/controllers/sentrace/ingestion_controller.rb +61 -24
  7. data/app/controllers/sentrace/internal/base_controller.rb +12 -1
  8. data/app/controllers/sentrace/internal/events_controller.rb +8 -8
  9. data/app/controllers/sentrace/internal/issues_controller.rb +13 -13
  10. data/app/controllers/sentrace/internal/projects_controller.rb +15 -8
  11. data/app/controllers/sentrace/internal/stats_controller.rb +16 -1
  12. data/app/controllers/sentrace/mcp_controller.rb +9 -5
  13. data/app/models/sentrace/mcp_token.rb +16 -3
  14. data/app/models/sentrace/project_key.rb +24 -3
  15. data/config/routes.rb +1 -1
  16. data/lib/sentrace/breadcrumbs/active_support_logger.rb +6 -1
  17. data/lib/sentrace/configuration.rb +33 -3
  18. data/lib/sentrace/event_builder.rb +3 -0
  19. data/lib/sentrace/ingestion/envelope_parser.rb +36 -7
  20. data/lib/sentrace/ingestion/event_normalizer.rb +17 -4
  21. data/lib/sentrace/ingestion/processor.rb +5 -1
  22. data/lib/sentrace/ingestion/sanitizer.rb +79 -25
  23. data/lib/sentrace/issues/fingerprint.rb +13 -6
  24. data/lib/sentrace/mcp/environment_router.rb +2 -1
  25. data/lib/sentrace/mcp/local_backend.rb +9 -3
  26. data/lib/sentrace/mcp/remote_http_client.rb +65 -15
  27. data/lib/sentrace/mcp/server.rb +20 -5
  28. data/lib/sentrace/request_security.rb +126 -0
  29. data/lib/sentrace/storage_stats.rb +1 -1
  30. data/lib/sentrace/version.rb +1 -1
  31. data/lib/sentrace.rb +1 -0
  32. metadata +3 -2
@@ -5,6 +5,8 @@ module Sentrace
5
5
  class IngestionController < ApplicationController
6
6
  GZIP_CHUNK_BYTES = 16 * 1024
7
7
  HEADER_PEEK_BYTES = 16 * 1024
8
+ MAX_AUTH_HEADER_BYTES = 4 * 1024
9
+ MAX_AUTH_HEADER_PAIRS = 16
8
10
 
9
11
  before_action :apply_cors_headers
10
12
 
@@ -23,8 +25,30 @@ module Sentrace
23
25
  return render json: { error: "Payload too large" }, status: 413
24
26
  end
25
27
 
28
+ project_id = parse_positive_project_id(params[:project_id])
29
+ unless project_id
30
+ return render json: { error: "Unauthorized" }, status: :unauthorized
31
+ end
32
+
33
+ cred_source, pub_key, secret_key = extract_header_or_query_credentials
34
+ if cred_source == :invalid
35
+ return render json: { error: "Unauthorized" }, status: :unauthorized
36
+ end
37
+
38
+ matched_key = nil
39
+ if cred_source == :supplied
40
+ matched_key = ProjectKey.authenticate_public_key(
41
+ project_id: project_id,
42
+ public_key: pub_key,
43
+ secret: secret_key
44
+ )
45
+ unless matched_key
46
+ return render json: { error: "Unauthorized" }, status: :unauthorized
47
+ end
48
+ end
49
+
26
50
  raw_bytes = read_bounded_stream(request.body, max_size)
27
- matched_key = authenticate_request(raw_bytes, max_size: max_size)
51
+ matched_key ||= authenticate_envelope_dsn(raw_bytes, project_id: project_id, max_size: max_size)
28
52
  unless matched_key
29
53
  return render json: { error: "Unauthorized" }, status: :unauthorized
30
54
  end
@@ -103,55 +127,68 @@ module Sentrace
103
127
  raise EnvelopeParseError, "Malformed gzip stream"
104
128
  end
105
129
 
106
- def authenticate_request(raw_bytes, max_size:)
107
- project_id = Integer(params[:project_id].to_s, 10)
108
- return nil if project_id <= 0
130
+ def parse_positive_project_id(raw_project_id)
131
+ return nil unless raw_project_id.is_a?(String) || raw_project_id.is_a?(Integer)
109
132
 
110
- pub_key, secret_key = extract_credentials(raw_bytes, project_id: project_id, max_size: max_size)
111
- return nil if pub_key.blank?
133
+ str = raw_project_id.to_s
134
+ return nil if str.bytesize > 20
112
135
 
113
- ProjectKey.authenticate_public_key(
114
- project_id: project_id,
115
- public_key: pub_key,
116
- secret: secret_key
117
- )
136
+ parsed = Integer(str, 10)
137
+ parsed.positive? ? parsed : nil
118
138
  rescue ArgumentError, TypeError
119
139
  nil
120
140
  end
121
141
 
122
- def extract_credentials(raw_bytes, project_id:, max_size:)
142
+ def extract_header_or_query_credentials
123
143
  auth_header = request.headers["X-Sentry-Auth"].presence || sentry_authorization_header
124
144
  if auth_header
145
+ return [ :invalid, nil, nil ] if auth_header.bytesize > MAX_AUTH_HEADER_BYTES
146
+
125
147
  parsed = parse_sentry_auth_header(auth_header)
126
- return [ parsed["sentry_key"], parsed["sentry_secret"] ] if parsed["sentry_key"].present?
148
+ if parsed["sentry_key"].present?
149
+ return [ :supplied, parsed["sentry_key"], parsed["sentry_secret"] ]
150
+ end
127
151
  end
128
152
 
129
- if request.query_parameters["sentry_key"].present?
130
- return [
131
- request.query_parameters["sentry_key"].to_s,
132
- request.query_parameters["sentry_secret"]&.to_s
133
- ]
153
+ if request.query_parameters.key?("sentry_key")
154
+ raw_key = request.query_parameters["sentry_key"]
155
+ raw_secret = request.query_parameters["sentry_secret"]
156
+ if !raw_key.is_a?(String) || (!raw_secret.nil? && !raw_secret.is_a?(String))
157
+ return [ :invalid, nil, nil ]
158
+ end
159
+
160
+ if raw_key.present?
161
+ return [ :supplied, raw_key, raw_secret ]
162
+ end
134
163
  end
135
164
 
165
+ [ :none, nil, nil ]
166
+ end
167
+
168
+ def authenticate_envelope_dsn(raw_bytes, project_id:, max_size:)
136
169
  dsn_string = extract_dsn_from_envelope_prefix(raw_bytes, max_size: max_size)
137
- return [ nil, nil ] if dsn_string.blank?
170
+ return nil if dsn_string.blank?
138
171
 
139
172
  parsed_dsn = Dsn.parse(dsn_string)
140
- return [ nil, nil ] unless parsed_dsn.project_id.to_i == project_id
173
+ return nil unless parsed_dsn.project_id.to_i == project_id
141
174
 
142
- [ parsed_dsn.public_key, parsed_dsn.secret_key ]
175
+ ProjectKey.authenticate_public_key(
176
+ project_id: project_id,
177
+ public_key: parsed_dsn.public_key,
178
+ secret: parsed_dsn.secret_key
179
+ )
143
180
  rescue InvalidDsnError
144
- [ nil, nil ]
181
+ nil
145
182
  end
146
183
 
147
184
  def sentry_authorization_header
148
185
  raw = request.headers["Authorization"].to_s
149
- raw if raw.match?(/\ASentry\s+/i)
186
+ raw if raw.bytesize <= MAX_AUTH_HEADER_BYTES && raw.match?(/\ASentry\s+/i)
150
187
  end
151
188
 
152
189
  def parse_sentry_auth_header(raw_header)
153
190
  stripped = raw_header.to_s.sub(/\ASentry\s+/i, "")
154
- stripped.split(",").each_with_object({}) do |pair, acc|
191
+ stripped.split(",", MAX_AUTH_HEADER_PAIRS + 1).first(MAX_AUTH_HEADER_PAIRS).each_with_object({}) do |pair, acc|
155
192
  key, val = pair.split("=", 2)
156
193
  next if key.nil? || val.nil?
157
194
 
@@ -1,6 +1,7 @@
1
1
  module Sentrace
2
2
  module Internal
3
3
  class BaseController < ApplicationController
4
+ before_action :verify_request_origin_and_csrf!
4
5
  before_action :authenticate_internal_request!
5
6
 
6
7
  rescue_from ActiveRecord::RecordNotFound do |err|
@@ -20,6 +21,12 @@ module Sentrace
20
21
  end
21
22
 
22
23
  private
24
+ def verify_request_origin_and_csrf!
25
+ if RequestSecurity.forbidden_cross_origin?(request) || RequestSecurity.forbidden_cookie_csrf?(request)
26
+ render json: { error: "Forbidden" }, status: :forbidden
27
+ end
28
+ end
29
+
23
30
  def authenticate_internal_request!
24
31
  custom_auth = Sentrace.configuration.internal_authenticator
25
32
  if custom_auth
@@ -30,13 +37,17 @@ module Sentrace
30
37
  end
31
38
 
32
39
  auth_header = request.headers["Authorization"].to_s
33
- bearer = auth_header[/\ABearer\s+(\S+)\z/i, 1]
40
+ bearer = auth_header.bytesize <= 1024 ? auth_header[/\ABearer\s+(\S+)\z/i, 1] : nil
34
41
  return if McpToken.authenticate(bearer)
35
42
 
36
43
  response.set_header("WWW-Authenticate", 'Bearer realm="sentrace-internal"')
37
44
  render json: { error: "Unauthorized" }, status: :unauthorized
38
45
  end
39
46
 
47
+ def scalar_param(key)
48
+ RequestSecurity.scalar_param(params, key)
49
+ end
50
+
40
51
  def local_backend
41
52
  @local_backend ||= Mcp::LocalBackend.new(
42
53
  environment_name: Sentrace.configuration.deployment_environment.to_s
@@ -3,20 +3,20 @@ module Sentrace
3
3
  class EventsController < BaseController
4
4
  def index
5
5
  payload = local_backend.list_events(
6
- project_id: params[:project_id],
7
- issue_id: params[:issue_id],
8
- since: params[:since],
9
- until: params[:until],
10
- limit: params[:limit],
11
- cursor: params[:cursor]
6
+ project_id: scalar_param(:project_id),
7
+ issue_id: scalar_param(:issue_id),
8
+ since: scalar_param(:since),
9
+ until: scalar_param(:until),
10
+ limit: scalar_param(:limit),
11
+ cursor: scalar_param(:cursor)
12
12
  )
13
13
  render json: payload
14
14
  end
15
15
 
16
16
  def show
17
17
  payload = local_backend.get_event(
18
- event_id: params[:id],
19
- project_id: params[:project_id]
18
+ event_id: scalar_param(:id),
19
+ project_id: scalar_param(:project_id)
20
20
  )
21
21
  render json: payload
22
22
  end
@@ -3,31 +3,31 @@ module Sentrace
3
3
  class IssuesController < BaseController
4
4
  def index
5
5
  payload = local_backend.list_issues(
6
- project_id: params[:project_id],
7
- status: params[:status],
8
- level: params[:level],
9
- release: params[:release],
10
- since: params[:since],
11
- until: params[:until],
12
- limit: params[:limit],
13
- cursor: params[:cursor]
6
+ project_id: scalar_param(:project_id),
7
+ status: scalar_param(:status),
8
+ level: scalar_param(:level),
9
+ release: scalar_param(:release),
10
+ since: scalar_param(:since),
11
+ until: scalar_param(:until),
12
+ limit: scalar_param(:limit),
13
+ cursor: scalar_param(:cursor)
14
14
  )
15
15
  render json: payload
16
16
  end
17
17
 
18
18
  def show
19
19
  payload = local_backend.get_issue(
20
- issue_id: params[:id],
21
- project_id: params[:project_id]
20
+ issue_id: scalar_param(:id),
21
+ project_id: scalar_param(:project_id)
22
22
  )
23
23
  render json: payload
24
24
  end
25
25
 
26
26
  def update
27
27
  payload = local_backend.update_issue_status(
28
- issue_id: params[:id],
29
- status: params[:status],
30
- project_id: params[:project_id]
28
+ issue_id: scalar_param(:id),
29
+ status: scalar_param(:status),
30
+ project_id: scalar_param(:project_id)
31
31
  )
32
32
  render json: payload
33
33
  end
@@ -7,32 +7,32 @@ module Sentrace
7
7
  end
8
8
 
9
9
  def show
10
- project = Project.includes(:project_keys).find(params[:id])
10
+ project = Project.includes(:project_keys).find(scalar_param(:id))
11
11
  render json: { project: serialize_project(project) }
12
12
  end
13
13
 
14
14
  def create
15
- slug = params[:slug].to_s.strip
15
+ slug = scalar_param(:slug).to_s.strip
16
16
  if slug.empty?
17
17
  return render json: { error: "slug is required" }, status: 422
18
18
  end
19
19
 
20
- project, key = Project.provision!(slug: slug, name: params[:name])
20
+ project, key = Project.provision!(slug: slug, name: scalar_param(:name))
21
21
  render json: { project: serialize_project(project, key_override: key) }, status: :created
22
22
  end
23
23
 
24
24
  def update
25
- project = Project.find(params[:id])
25
+ project = Project.find(scalar_param(:id))
26
26
  attrs = {}
27
- attrs[:name] = params[:name] if params.key?(:name)
28
- attrs[:slug] = params[:slug] if params.key?(:slug)
27
+ attrs[:name] = scalar_param(:name) if params.key?(:name)
28
+ attrs[:slug] = scalar_param(:slug) if params.key?(:slug)
29
29
  project.update!(attrs) if attrs.any?
30
30
 
31
31
  render json: { project: serialize_project(project) }
32
32
  end
33
33
 
34
34
  def destroy
35
- project = Project.find(params[:id])
35
+ project = Project.find(scalar_param(:id))
36
36
  project.destroy!
37
37
  head :no_content
38
38
  end
@@ -41,7 +41,14 @@ module Sentrace
41
41
  def serialize_project(project, key_override: nil)
42
42
  active_key = key_override || project.active_key
43
43
  base_url = "#{request.base_url}#{Sentrace::Engine.routes.find_script_name({})}"
44
- dsn = active_key ? Dsn.build(base_url: base_url, public_key: active_key.public_key, project_id: project.id).to_s : nil
44
+ dsn =
45
+ if active_key
46
+ begin
47
+ Dsn.build(base_url: base_url, public_key: active_key.public_key, project_id: project.id).to_s
48
+ rescue InvalidDsnError
49
+ nil
50
+ end
51
+ end
45
52
 
46
53
  {
47
54
  id: project.id,
@@ -1,10 +1,25 @@
1
1
  module Sentrace
2
2
  module Internal
3
3
  class StatsController < BaseController
4
+ MAX_STATS_DAYS = 365
5
+
4
6
  def show
5
- days = params[:days] ? params[:days].to_i : 30
7
+ raw_days = scalar_param(:days)
8
+ days = raw_days.nil? || raw_days.to_s.strip.empty? ? 30 : parse_days!(raw_days)
6
9
  render json: StorageStats.collect(days: days)
7
10
  end
11
+
12
+ private
13
+ def parse_days!(raw_days)
14
+ parsed = Integer(raw_days.to_s.strip, 10)
15
+ unless (1..MAX_STATS_DAYS).cover?(parsed)
16
+ raise McpInvalidParamsError, "days must be between 1 and #{MAX_STATS_DAYS}"
17
+ end
18
+
19
+ parsed
20
+ rescue ArgumentError, TypeError
21
+ raise McpInvalidParamsError, "days must be between 1 and #{MAX_STATS_DAYS}"
22
+ end
8
23
  end
9
24
  end
10
25
  end
@@ -10,6 +10,10 @@ module Sentrace
10
10
  return render json: { error: "HTTPS is required for non-local MCP endpoints" }, status: :forbidden
11
11
  end
12
12
 
13
+ if RequestSecurity.forbidden_cross_origin?(request)
14
+ return render json: { error: "Cross-origin MCP requests are forbidden" }, status: :forbidden
15
+ end
16
+
13
17
  token_record = authenticate_bearer_token
14
18
  unless token_record
15
19
  response.set_header("WWW-Authenticate", 'Bearer realm="sentrace-mcp"')
@@ -32,13 +36,13 @@ module Sentrace
32
36
 
33
37
  private
34
38
  def https_or_loopback?
35
- return true if request.ssl?
36
-
37
- Configuration::LOOPBACK_HOSTS.include?(request.host.to_s.downcase)
39
+ RequestSecurity.https_or_loopback?(request)
38
40
  end
39
41
 
40
42
  def authenticate_bearer_token
41
43
  auth_header = request.headers["Authorization"].to_s
44
+ return nil if auth_header.bytesize > 1024
45
+
42
46
  match = auth_header.match(/\ABearer\s+(\S+)\z/i)
43
47
  return nil unless match
44
48
 
@@ -57,11 +61,11 @@ module Sentrace
57
61
  def write_rack_response(rack_status, rack_headers, rack_body)
58
62
  rack_headers.each do |key, value|
59
63
  next if key.to_s.casecmp("content-length").zero?
60
- next if key.to_s.casecmp("cache-control").zero?
64
+ next if RequestSecurity.security_header_key?(key)
61
65
 
62
66
  response.set_header(key, value)
63
67
  end
64
- response.set_header("Cache-Control", "no-store")
68
+ RequestSecurity.apply_security_headers!(response)
65
69
 
66
70
  chunks = []
67
71
  rack_body.each { |chunk| chunks << chunk.to_s }
@@ -5,6 +5,8 @@ module Sentrace
5
5
  class McpToken < ApplicationRecord
6
6
  TOKEN_PREFIX_HEADER = "snt_mcp_".freeze
7
7
  PREFIX_LENGTH = 12
8
+ MAX_RAW_TOKEN_BYTES = 512
9
+ DUMMY_DIGEST = ("0" * 64).freeze
8
10
  ENSURED_TOKEN_FORMAT = /\Asnt_mcp_[A-Za-z0-9_-]{24,256}\z/
9
11
 
10
12
  scope :active, -> { where(active: true, revoked_at: nil) }
@@ -35,14 +37,25 @@ module Sentrace
35
37
 
36
38
  def authenticate(raw_token)
37
39
  return nil if raw_token.blank?
40
+ return nil unless raw_token.is_a?(String) || raw_token.is_a?(Symbol)
38
41
 
39
42
  provided = raw_token.to_s
40
- return nil unless provided.start_with?(TOKEN_PREFIX_HEADER)
43
+ return nil if provided.bytesize > MAX_RAW_TOKEN_BYTES
41
44
 
42
45
  candidate_digest = digest_token(provided)
43
- matched = nil
46
+ unless provided.start_with?(TOKEN_PREFIX_HEADER)
47
+ ActiveSupport::SecurityUtils.secure_compare(candidate_digest, DUMMY_DIGEST)
48
+ return nil
49
+ end
44
50
 
45
- active.to_a.each do |record|
51
+ records = active.to_a
52
+ if records.empty?
53
+ ActiveSupport::SecurityUtils.secure_compare(candidate_digest, DUMMY_DIGEST)
54
+ return nil
55
+ end
56
+
57
+ matched = nil
58
+ records.each do |record|
46
59
  if record.token_digest.bytesize == candidate_digest.bytesize &&
47
60
  ActiveSupport::SecurityUtils.secure_compare(record.token_digest, candidate_digest)
48
61
  matched = record
@@ -3,6 +3,10 @@ require "securerandom"
3
3
 
4
4
  module Sentrace
5
5
  class ProjectKey < ApplicationRecord
6
+ MAX_PUBLIC_KEY_INPUT_BYTES = 128
7
+ MAX_SECRET_INPUT_BYTES = 512
8
+ DUMMY_DIGEST = ("0" * 64).freeze
9
+
6
10
  belongs_to :project
7
11
 
8
12
  scope :active, -> { where(active: true, revoked_at: nil) }
@@ -21,13 +25,28 @@ module Sentrace
21
25
 
22
26
  def authenticate_public_key(project_id:, public_key:, secret: nil)
23
27
  return nil if project_id.blank? || public_key.blank?
28
+ return nil unless public_key.is_a?(String) || public_key.is_a?(Symbol)
29
+ return nil if !secret.nil? && !secret.is_a?(String) && !secret.is_a?(Symbol)
24
30
 
25
31
  provided_pub = public_key.to_s
32
+ return nil if provided_pub.bytesize > MAX_PUBLIC_KEY_INPUT_BYTES
33
+ return nil if !secret.nil? && secret.to_s.bytesize > MAX_SECRET_INPUT_BYTES
34
+
35
+ provided_pub_digest = digest_secret(provided_pub)
26
36
  candidates = active.where(project_id: project_id).to_a
37
+ if candidates.empty?
38
+ ActiveSupport::SecurityUtils.secure_compare(provided_pub_digest, DUMMY_DIGEST)
39
+ return nil
40
+ end
27
41
 
28
- matched = candidates.find do |key|
29
- key.public_key.bytesize == provided_pub.bytesize &&
30
- ActiveSupport::SecurityUtils.secure_compare(key.public_key, provided_pub)
42
+ matched = nil
43
+ candidates.each do |key|
44
+ candidate_pub_digest = digest_secret(key.public_key)
45
+ if ActiveSupport::SecurityUtils.secure_compare(candidate_pub_digest, provided_pub_digest) &&
46
+ key.public_key.bytesize == provided_pub.bytesize &&
47
+ ActiveSupport::SecurityUtils.secure_compare(key.public_key, provided_pub)
48
+ matched = key
49
+ end
31
50
  end
32
51
 
33
52
  return nil unless matched
@@ -44,6 +63,8 @@ module Sentrace
44
63
 
45
64
  def verify_secret(candidate)
46
65
  return false if secret_digest.blank? || candidate.blank?
66
+ return false unless candidate.is_a?(String) || candidate.is_a?(Symbol)
67
+ return false if candidate.to_s.bytesize > MAX_SECRET_INPUT_BYTES
47
68
 
48
69
  candidate_digest = self.class.digest_secret(candidate)
49
70
  secret_digest.bytesize == candidate_digest.bytesize &&
data/config/routes.rb CHANGED
@@ -4,7 +4,7 @@ Sentrace::Engine.routes.draw do
4
4
  match "/mcp", to: "mcp#handle", via: [ :post, :get, :delete ]
5
5
 
6
6
  namespace :internal do
7
- resources :projects
7
+ resources :projects, only: [ :index, :show, :create, :update, :destroy ]
8
8
  resources :issues, only: [ :index, :show, :update ]
9
9
  resources :events, only: [ :index, :show ]
10
10
  resource :stats, only: [ :show ], controller: "stats"
@@ -2,6 +2,8 @@ module Sentrace
2
2
  module Breadcrumbs
3
3
  module ActiveSupportLogger
4
4
  IGNORED_SQL_NAMES = %w[SCHEMA TRANSACTION EXPLAIN].freeze
5
+ MAX_RAW_SQL_BYTES = 8192
6
+ SQL_DOLLAR_QUOTED_LITERAL = /\$((?:[A-Za-z_][A-Za-z0-9_]*)?)\$[\s\S]*?\$\1\$/
5
7
  SQL_SINGLE_QUOTED_LITERAL = /'(?:''|\\'|[^'])*'/
6
8
  SQL_OPERATION_REGEX = /\A\s*([A-Za-z]+)/
7
9
 
@@ -111,7 +113,10 @@ module Sentrace
111
113
  end
112
114
 
113
115
  def sanitize_sql_statement(sql)
114
- masked = sql.dup.force_encoding(Encoding::UTF_8).scrub.gsub(SQL_SINGLE_QUOTED_LITERAL, "'?'")
116
+ bounded_sql = Ingestion::EventNormalizer.truncate_utf8_bytes(sql, MAX_RAW_SQL_BYTES).to_s
117
+ masked = bounded_sql
118
+ .gsub(SQL_DOLLAR_QUOTED_LITERAL, "'?'")
119
+ .gsub(SQL_SINGLE_QUOTED_LITERAL, "'?'")
115
120
  collapsed = masked.gsub(/\s+/, " ").strip
116
121
  Ingestion::EventNormalizer.truncate_utf8_bytes(collapsed, 256)
117
122
  end
@@ -36,6 +36,8 @@ module Sentrace
36
36
  SUPPORTED_CAPTURE_DISPATCH_MODES = %i[async inline].freeze
37
37
 
38
38
  LOOPBACK_HOSTS = %w[localhost 127.0.0.1 ::1 [::1]].freeze
39
+ DEFAULT_MAX_EVENTS_PER_ENVELOPE = 10
40
+ DEFAULT_MAX_ENVELOPE_ITEMS = 50
39
41
 
40
42
  POSITIVE_NUMERIC_ATTRIBUTES = %i[
41
43
  retention_period
@@ -53,6 +55,12 @@ module Sentrace
53
55
  remote_ping_timeout
54
56
  ].freeze
55
57
 
58
+ POSITIVE_INTEGER_ATTRIBUTES = %i[
59
+ retention_batch_size
60
+ max_events_per_envelope
61
+ max_envelope_items
62
+ ].freeze
63
+
56
64
  EnvironmentDefinition = Data.define(:name, :transport, :url, :token, :timeout) do
57
65
  def inspect
58
66
  masked_token = token ? "[REDACTED]" : "nil"
@@ -78,6 +86,8 @@ module Sentrace
78
86
  :orphan_issue_retention_period,
79
87
  :retention_batch_size,
80
88
  :max_envelope_size,
89
+ :max_events_per_envelope,
90
+ :max_envelope_items,
81
91
  :max_message_bytes,
82
92
  :max_stack_frames,
83
93
  :max_breadcrumbs,
@@ -117,6 +127,8 @@ module Sentrace
117
127
  @orphan_issue_retention_period = 7.days
118
128
  @retention_batch_size = 1_000
119
129
  @max_envelope_size = 1.megabyte
130
+ @max_events_per_envelope = DEFAULT_MAX_EVENTS_PER_ENVELOPE
131
+ @max_envelope_items = DEFAULT_MAX_ENVELOPE_ITEMS
120
132
  @max_message_bytes = 4.kilobytes
121
133
  @max_stack_frames = 50
122
134
  @max_breadcrumbs = 20
@@ -191,8 +203,11 @@ module Sentrace
191
203
  raise ConfigurationError, "retain_user_fields must be an Array of field names"
192
204
  end
193
205
 
194
- unless retention_batch_size.is_a?(Integer) && retention_batch_size.positive?
195
- raise ConfigurationError, "retention_batch_size must be a positive Integer (got #{retention_batch_size.inspect})"
206
+ POSITIVE_INTEGER_ATTRIBUTES.each do |attr|
207
+ val = public_send(attr)
208
+ unless val.is_a?(Integer) && val.positive?
209
+ raise ConfigurationError, "#{attr} must be a positive Integer (got #{val.inspect})"
210
+ end
196
211
  end
197
212
 
198
213
  if !sanitizer.nil? && !sanitizer.respond_to?(:call)
@@ -383,6 +398,16 @@ module Sentrace
383
398
  raise ConfigurationError, "environment #{env_def.name.inspect} timeout must be a positive number"
384
399
  end
385
400
 
401
+ if !env_def.token.nil? && !env_def.token.is_a?(String)
402
+ raise ConfigurationError, "environment #{env_def.name.inspect} token must be a String or nil"
403
+ end
404
+
405
+ raw_token = env_def.token.to_s.strip
406
+ if !raw_token.empty? && raw_token.match?(/[\s\x00-\x1F\x7F]/)
407
+ raise ConfigurationError,
408
+ "environment #{env_def.name.inspect} token must not contain whitespace or control characters"
409
+ end
410
+
386
411
  raw_url = env_def.url.to_s.strip
387
412
  return if raw_url.empty?
388
413
 
@@ -391,7 +416,12 @@ module Sentrace
391
416
  raise ConfigurationError, "environment #{env_def.name.inspect} url #{env_def.url.inspect} is invalid"
392
417
  end
393
418
 
394
- if uri.scheme != "https" && !LOOPBACK_HOSTS.include?(uri.host.downcase)
419
+ if uri.userinfo || uri.fragment
420
+ raise ConfigurationError,
421
+ "environment #{env_def.name.inspect} url must not contain embedded credentials or fragments"
422
+ end
423
+
424
+ if uri.scheme != "https" && !RequestSecurity.loopback_host?(uri.host)
395
425
  raise ConfigurationError,
396
426
  "environment #{env_def.name.inspect} requires HTTPS for non-local host #{uri.host.inspect}"
397
427
  end
@@ -5,6 +5,7 @@ module Sentrace
5
5
  class EventBuilder
6
6
  SDK_NAME = "sentrace.ruby"
7
7
  MAX_CAUSE_DEPTH = 5
8
+ MAX_BACKTRACE_LINE_BYTES = 4096
8
9
  BACKTRACE_LINE_REGEX = /\A(?<file>.+?):(?<line>\d+)(?::in [`'](?<fn>.+)'|:in (?<fn2>.+))?\z/
9
10
 
10
11
  class << self
@@ -211,6 +212,8 @@ module Sentrace
211
212
  end
212
213
 
213
214
  def parse_backtrace_line(line, app_root)
215
+ return nil if line.bytesize > MAX_BACKTRACE_LINE_BYTES
216
+
214
217
  match = BACKTRACE_LINE_REGEX.match(line)
215
218
  return nil unless match
216
219