exis_ray 0.11.0 → 1.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.
@@ -26,8 +26,10 @@ module ExisRay
26
26
  # o valores sin comillas que se extienden hasta el próximo token key= o fin de string.
27
27
  KV_PARSE_RE = /(\w+)=("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|(?:(?!\s+\w+=).)+)/
28
28
 
29
- # Claves sensibles que deben filtrarse automáticamente según el estándar de Gabriel.
30
- SENSITIVE_KEYS = /password|pass|passwd|secret|token|api_key|auth/i
29
+ # Claves que pone exis_ray y nunca se recortan para cumplir el tope de línea: identifican la línea y su
30
+ # traza. También son las que quedan si tapar falla.
31
+ CONTEXT_KEYS = %w[time level severity_number service service_version deployment_environment request_id
32
+ root_id trace_id sidekiq_job task source user_id isp_id correlation_id tags].freeze
31
33
 
32
34
  # Mapeo de severity_text OTel a SeverityNumber del Log Data Model.
33
35
  # https://opentelemetry.io/docs/specs/otel/log/data-model/#field-severitynumber
@@ -47,7 +49,24 @@ module ExisRay
47
49
  # @param msg [String, Hash, Object] El mensaje a registrar. Puede ser un Hash (inyectado por Lograge) o un String.
48
50
  # @return [String] Una cadena en formato JSON terminada con un salto de línea (\n).
49
51
  def call(severity, timestamp, _progname, msg)
50
- payload = {
52
+ context = build_context(severity, timestamp)
53
+ payload = context.dup
54
+ sanitizer = ExisRay::LogSanitizer.new(ExisRay.configuration)
55
+ inject_log_fields(payload, sanitizer)
56
+ process_message(payload, msg, sanitizer)
57
+
58
+ limit_line(normalize_keys(payload))
59
+ rescue StandardError, SystemStackError => e
60
+ fallback_message(context, severity, timestamp, e)
61
+ end
62
+
63
+ private
64
+
65
+ # Lo que exis_ray pone en toda línea: tiempo, nivel, servicio, traza y negocio. No pasa por el sanitizer.
66
+ #
67
+ # @return [Hash]
68
+ def build_context(severity, timestamp)
69
+ context = {
51
70
  time: timestamp&.utc&.iso8601 || Time.now.utc.iso8601,
52
71
  level: severity,
53
72
  severity_number: SEVERITY_NUMBER[severity],
@@ -55,18 +74,65 @@ module ExisRay
55
74
  service_version: service_version,
56
75
  deployment_environment: deployment_environment
57
76
  }
77
+ inject_tracer_context(context)
78
+ inject_business_context(context)
79
+ inject_current_tags(context)
80
+ context
81
+ end
82
+
83
+ # Escribe la línea con el tope de {Configuration#max_line_bytes}, sin romper el JSON: reemplaza primero los
84
+ # campos más grandes que no son de contexto ni de diagnóstico, después recorta los de diagnóstico, y si
85
+ # aun así no entra, deja el contexto con `truncated` (sin `tags` si ni eso entra).
86
+ #
87
+ # @param payload [Hash{String => Object}]
88
+ # @return [String]
89
+ def limit_line(payload)
90
+ max = ExisRay.configuration.max_line_bytes
91
+ line = generate(payload)
92
+ return line if line.bytesize <= max
93
+
94
+ replace_largest_fields(payload, max)
95
+ shrink_diagnostic_fields(payload, max)
96
+ line = generate(payload)
97
+ return line if line.bytesize <= max
98
+
99
+ context = payload.slice(*CONTEXT_KEYS).merge("truncated" => true)
100
+ line = generate(context)
101
+ line.bytesize <= max ? line : generate(context.except("tags"))
102
+ end
58
103
 
59
- inject_tracer_context(payload)
60
- inject_business_context(payload)
61
- inject_current_tags(payload)
62
- process_message(payload, msg)
104
+ def replace_largest_fields(payload, max)
105
+ sizes = (payload.keys - CONTEXT_KEYS - LogSanitizer::DIAGNOSTIC_KEYS).to_h { |key| [key, generate_value(payload[key]).bytesize] }
106
+ total = generate(payload).bytesize
107
+ sizes.sort_by { |_, size| -size }.each do |key, size|
108
+ break if total <= max
63
109
 
64
- "#{JSON.generate(normalize_keys(payload), { ascii_only: false })}\n"
65
- rescue StandardError
66
- fallback_message(severity, timestamp, msg)
110
+ marker = "[TRUNCATED size=#{size}]"
111
+ next if marker.bytesize + 2 >= size
112
+
113
+ payload[key] = marker
114
+ total -= size - (marker.bytesize + 2)
115
+ end
67
116
  end
68
117
 
69
- private
118
+ def shrink_diagnostic_fields(payload, max)
119
+ (LogSanitizer::DIAGNOSTIC_KEYS & payload.keys).each do |key|
120
+ excess = generate(payload).bytesize - max
121
+ break if excess <= 0
122
+
123
+ value = payload[key].is_a?(String) ? payload[key] : generate_value(payload[key])
124
+ keep = [value.bytesize - excess - 64, 0].max
125
+ payload[key] = LogSanitizer.truncate_bytes(value, keep)
126
+ end
127
+ end
128
+
129
+ def generate(payload)
130
+ "#{JSON.generate(payload, { ascii_only: false })}\n"
131
+ end
132
+
133
+ def generate_value(value)
134
+ JSON.generate(value, { ascii_only: false })
135
+ end
70
136
 
71
137
  # Normaliza todas las claves del payload a strings y deduplica con precedencia
72
138
  # "última inserción gana" (developer payload pisa contexto canónico inyectado
@@ -94,23 +160,19 @@ module ExisRay
94
160
  ExisRay.configuration.deployment_environment
95
161
  end
96
162
 
97
- # Genera un JSON de fallback cuando el formateo principal falla.
98
- # Nunca debe lanzar una excepción.
163
+ # La línea cuando tapar o escribir falla: el contexto y `filter_error`, nunca el mensaje (ADR-131).
164
+ # Nunca lanza una excepción.
99
165
  #
166
+ # @param context [Hash, nil] el contexto ya armado, si se llegó a armar.
100
167
  # @param severity [String]
101
168
  # @param timestamp [Time]
102
- # @param msg [Object]
169
+ # @param error [Exception]
103
170
  # @return [String]
104
- def fallback_message(severity, timestamp, msg)
105
- fallback = {
106
- time: timestamp&.utc&.iso8601 || Time.now.utc.iso8601,
107
- level: severity,
108
- service: ExisRay::Tracer.service_name,
109
- body: msg.to_s[0..500]
110
- }
111
- "#{JSON.generate(fallback)}\n"
171
+ def fallback_message(context, severity, timestamp, error)
172
+ base = context || { time: timestamp&.utc&.iso8601 || Time.now.utc.iso8601, level: severity }
173
+ generate(normalize_keys(base).slice(*CONTEXT_KEYS).merge("filter_error" => error.class.name))
112
174
  rescue StandardError
113
- "#{JSON.generate({ time: Time.now.utc.iso8601, level: severity, body: "log_error" })}\n"
175
+ "#{JSON.generate({ time: Time.now.utc.iso8601, level: severity, filter_error: "log_error" })}\n"
114
176
  end
115
177
 
116
178
  # Inyecta los identificadores de trazabilidad distribuida en el payload.
@@ -145,27 +207,26 @@ module ExisRay
145
207
  payload[:isp_id] = curr.isp_id if curr.respond_to?(:isp_id) && !curr.isp_id.nil?
146
208
 
147
209
  payload[:correlation_id] = curr.correlation_id if curr.respond_to?(:correlation_id) && curr.correlation_id
148
-
149
- inject_log_fields(payload, curr)
150
210
  end
151
211
 
152
- # Mergea el resultado de `Current.log_fields` al payload, aplicando el mismo
153
- # filtrado de claves sensibles que el resto del formatter. Si la subclass del
154
- # host overrideó el hook y revienta, el error se traga: logging nunca debe
155
- # afectar el flujo principal.
212
+ # Mergea el resultado de `Current.log_fields` al payload, tapado por el sanitizer. Si la subclass del host
213
+ # overrideó el hook y revienta, el error se traga: logging nunca debe afectar el flujo principal.
156
214
  #
157
215
  # @param payload [Hash]
158
- # @param curr [Class] La clase Current configurada por la app host.
216
+ # @param sanitizer [ExisRay::LogSanitizer]
159
217
  # @return [void]
160
- def inject_log_fields(payload, curr)
218
+ def inject_log_fields(payload, sanitizer)
219
+ curr = ExisRay.current_class
161
220
  return unless curr.respond_to?(:log_fields)
162
221
 
163
- fields = curr.log_fields
222
+ fields = begin
223
+ curr.log_fields
224
+ rescue StandardError
225
+ nil
226
+ end
164
227
  return if fields.nil? || fields.empty?
165
228
 
166
- payload.merge!(filter_sensitive_hash(fields))
167
- rescue StandardError
168
- nil
229
+ payload.merge!(cast_deep(sanitizer.call(fields)))
169
230
  end
170
231
 
171
232
  # Inyecta cualquier etiqueta nativa (tags) de Rails que esté presente en el hilo actual.
@@ -186,18 +247,20 @@ module ExisRay
186
247
  # entre comillas (ej: message="algo salió mal"). Si el String no sigue ese formato, se asigna
187
248
  # a la clave `:body` (OpenTelemetry log body).
188
249
  #
250
+ # Todo lo que viene del mensaje pasa por el sanitizer.
251
+ #
189
252
  # @param payload [Hash] El diccionario base del log.
190
253
  # @param msg [String, Hash, Object] El mensaje original recibido por el logger.
254
+ # @param sanitizer [ExisRay::LogSanitizer]
191
255
  # @return [void]
192
- def process_message(payload, msg)
256
+ def process_message(payload, msg, sanitizer)
193
257
  if msg.is_a?(Hash)
194
- # Filtramos las claves del Hash antes del merge
195
- payload.merge!(filter_sensitive_hash(msg))
258
+ payload.merge!(cast_deep(sanitizer.call(msg)))
196
259
  elsif msg.is_a?(String) && kv_string?(msg)
197
260
  parsed = parse_kv_string(msg)
198
- parsed.empty? ? payload[:body] = msg : payload.merge!(parsed)
261
+ parsed.empty? ? payload[:body] = sanitizer.call(msg) : payload.merge!(sanitizer.call(parsed))
199
262
  else
200
- payload[:body] = msg.to_s
263
+ payload[:body] = sanitizer.call(msg.to_s)
201
264
  end
202
265
  end
203
266
 
@@ -231,15 +294,30 @@ module ExisRay
231
294
  result
232
295
  end
233
296
 
234
- # Filtra un valor si la clave se considera sensible.
235
- # Si no es sensible, intenta castear el valor a número o a objeto JSON si corresponde.
297
+ # Castea a número o a objeto JSON los strings de un Hash o un Array, recursivamente (lo que hacía el filtro
298
+ # de 0.11.1 al recorrer el mensaje).
236
299
  #
237
- # @param key [String, Symbol]
238
- # @param value [Object]
300
+ # Corre sobre la salida del sanitizer, que ya tiene topes de profundidad y de nodos: por eso no los repite.
301
+ #
302
+ # @param obj [Object]
303
+ # @param key [String, Symbol, nil]
239
304
  # @return [Object]
240
- def cast_value(key, value)
241
- return "[FILTERED]" if key.to_s.match?(SENSITIVE_KEYS)
305
+ def cast_deep(obj, key = nil)
306
+ case obj
307
+ when Hash then obj.to_h { |k, v| [k, cast_deep(v, k)] }
308
+ when Array then obj.map { |element| cast_deep(element, key) }
309
+ when String then cast_value(key, obj)
310
+ else obj
311
+ end
312
+ end
242
313
 
314
+ # Castea el valor de un par `clave=valor` a número o a objeto JSON si corresponde. Qué se tapa lo decide
315
+ # el sanitizer después.
316
+ #
317
+ # @param _key [String, Symbol]
318
+ # @param value [Object]
319
+ # @return [Object]
320
+ def cast_value(_key, value)
243
321
  case value
244
322
  when /\A\d+\z/ then value.to_i
245
323
  when /\A\d+\.\d+\z/ then value.to_f
@@ -260,50 +338,5 @@ module ExisRay
260
338
  rescue JSON::ParserError
261
339
  value
262
340
  end
263
-
264
- # Filtra recursivamente un Hash que contenga claves sensibles.
265
- # Maneja valores anidados de tipo Hash o Array.
266
- # Detecta referencias circulares para evitar stack overflow.
267
- #
268
- # @param hash [Hash]
269
- # @param visited [Set] IDs de objetos ya visitados para detectar ciclos (O(1) lookup).
270
- # @return [Hash]
271
- def filter_sensitive_hash(hash, visited = Set.new)
272
- return {} if hash.nil?
273
- return {} if visited.include?(hash.object_id)
274
-
275
- visited |= Set.new([hash.object_id])
276
-
277
- hash.each_with_object({}) do |(k, v), result|
278
- result[k] = case v
279
- when Hash then filter_sensitive_hash(v, visited)
280
- when Array then filter_sensitive_array(k, v, visited)
281
- else cast_value(k, v)
282
- end
283
- end
284
- end
285
-
286
- # Filtra recursivamente los elementos de un Array, propagando la clave padre
287
- # para que el filtrado de claves sensibles se aplique a hashes anidados.
288
- # Detecta referencias circulares para evitar stack overflow.
289
- #
290
- # @param key [String, Symbol] Clave padre (para filtrado si el array no contiene hashes).
291
- # @param array [Array]
292
- # @param visited [Set] IDs de objetos ya visitados para detectar ciclos (O(1) lookup).
293
- # @return [Array]
294
- def filter_sensitive_array(key, array, visited = Set.new)
295
- return [] if array.nil?
296
- return [] if visited.include?(array.object_id)
297
-
298
- visited |= Set.new([array.object_id])
299
-
300
- array.map do |element|
301
- case element
302
- when Hash then filter_sensitive_hash(element, visited)
303
- when Array then filter_sensitive_array(key, element, visited)
304
- else cast_value(key, element)
305
- end
306
- end
307
- end
308
341
  end
309
342
  end
@@ -0,0 +1,253 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module ExisRay
6
+ # Tapa lo sensible y limita el tamaño de un mensaje de log, antes de escribirlo (ADR-131).
7
+ #
8
+ # Es el único lugar que decide qué se tapa: lo usan {JsonFormatter} y {SanitizingFormatter}.
9
+ # No muta lo que recibe: devuelve una copia.
10
+ #
11
+ # Qué se tapa:
12
+ # - una clave de un Hash que coincide (ver {#sensitive?}): su valor entero, aunque sea un Hash o un Array;
13
+ # - dentro de un string, `CLAVE=VALOR`, `CLAVE: VALOR` y `CLAVE => VALOR` con una clave que coincide, y el
14
+ # valor de `Bearer`/`Basic`, y la clave de una URL `esquema://usuario:clave@host`;
15
+ # - un string con JSON adentro se parsea, se tapa y se vuelve a escribir como string.
16
+ #
17
+ # Límites, después de tapar: {Configuration#max_value_chars} por string (salvo las claves de
18
+ # {DIAGNOSTIC_KEYS}), {Configuration#max_array_items} por array, y un string de más de
19
+ # {Configuration#max_traverse_bytes} se reemplaza entero sin recorrerlo. El tope por línea lo aplica cada
20
+ # formatter, porque depende de cómo escribe la línea.
21
+ class LogSanitizer
22
+ # Marcador de un valor tapado.
23
+ FILTERED = "[FILTERED]"
24
+
25
+ # El default de qué se tapa, por "contiene": el de exis_ray 0.11.1 más lo que tapaban bug_bunny y docker-swarm
26
+ # antes de delegarle el filtro a exis_ray (ADR-131), así ningún servicio pierde protección al actualizar.
27
+ # `[_-]` porque una clave puede venir como header (`X-Api-Key`) o como símbolo (`api_key`). El `data` de
28
+ # docker-swarm no está: es un falso positivo en casi todo, y lo declara cada servicio en `filtered_keys`.
29
+ DEFAULT_SENSITIVE = /password|pass|passwd|secret|token|api[_-]key|auth|credential|private[_-]key|csrf|session[_-]id/i
30
+
31
+ # El valor de un `CLAVE=VALOR` con clave sensible, entero: entre comillas, un `{…}` o `[…]` balanceado (un
32
+ # `Hash#inspect`), o hasta un espacio (sin cortar en `,` ni `&`: tapa de más antes que dejar ver una parte).
33
+ # Puede llevar adelante el esquema de un header `Authorization` (`Token abc`).
34
+ SENSITIVE_VALUE = <<~'REGEX'
35
+ (?<value>
36
+ (?:(?:bearer|basic|token|digest)\s+)?
37
+ (?:"(?:[^"\\]|\\.)*+"
38
+ |'(?:[^'\\]|\\.)*+'
39
+ |(?<brace>\{(?:[^{}]++|\g<brace>)*+\})
40
+ |(?<bracket>\[(?:[^\[\]]++|\g<bracket>)*+\])
41
+ |["'{\[]?[^\s"'}\]]+)
42
+ )
43
+ REGEX
44
+
45
+ # Un string que es entero una asignación `NOMBRE=valor` (el nombre sin espacios), como un elemento del `Env` de
46
+ # Docker. Con un nombre sensible se tapa hasta el final: el valor puede tener espacios o varias líneas (una
47
+ # clave PEM). Es la regla que tenía `docker-swarm` antes de delegar el filtro en exis_ray (ADR-131).
48
+ ASSIGNMENT = /\A(?<key>[^=\s]+)=/
49
+
50
+ # Lo que tiene que aparecer en el texto para que un `CLAVE=VALOR` o {AUTH_SCHEME} puedan coincidir.
51
+ KV_ANCHOR = /=|:/
52
+ AUTH_ANCHOR = /bearer|basic/i
53
+
54
+ # Credenciales de un header `Authorization` escritas como texto.
55
+ AUTH_SCHEME = %r{\b(?<scheme>Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+}i
56
+
57
+ # Credenciales en una URL (`esquema://usuario:clave@host`): se tapa la clave, hasta la última `@` antes del
58
+ # host (una `@` sin codificar en la clave no la corta). Una `/` sin codificar en la clave no se ve: esa URL ya
59
+ # es inválida.
60
+ URL_CREDENTIALS = %r{(?<prefix>\b[a-z][a-z0-9+.-]*://[^\s:/@]*:)[^\s/]+@}i
61
+
62
+ # El diagnóstico de la línea: no se recorta a {Configuration#max_value_chars}, y cuando la línea pasa de
63
+ # {Configuration#max_line_bytes} se recorta último, conservando el principio, en este orden. El primero se
64
+ # lleva todo el exceso: el mensaje va antes que el stacktrace porque suele ser el grande y su principio
65
+ # alcanza; el stacktrace es chico (20 frames) y recortado primero desaparecía entero (medido con un rechazo
66
+ # de AFIP de 8 KB). `event` va al final: identifica la línea.
67
+ DIAGNOSTIC_KEYS = %w[body message error_message exception.message exception.stacktrace event].freeze
68
+
69
+ # Profundidad y cantidad de nodos que se recorren; lo que pasa se reemplaza por un marcador.
70
+ MAX_DEPTH = 20
71
+ MAX_NODES = 10_000
72
+
73
+ # @param config [ExisRay::Configuration]
74
+ def initialize(config = ExisRay.configuration)
75
+ @config = config
76
+ @keys = Set.new(Array(config.filtered_keys).map { |key| key.to_s.downcase })
77
+ @unfiltered = Set.new(Array(config.unfiltered_keys).map { |key| key.to_s.downcase })
78
+ @key_value = self.class.key_value_regex(@keys, @unfiltered)
79
+ @nodes = 0
80
+ end
81
+
82
+ # @param obj [Object] el mensaje o un valor del mensaje.
83
+ # @return [Object] una copia con lo sensible tapado y los límites aplicados.
84
+ def call(obj)
85
+ @nodes = 0
86
+ walk(obj, nil, 0)
87
+ end
88
+
89
+ # Recorta un texto a `bytes` en un borde UTF-8 válido y le agrega el marcador con el tamaño original.
90
+ #
91
+ # @param text [String]
92
+ # @param bytes [Integer]
93
+ # @return [String]
94
+ def self.truncate_bytes(text, bytes)
95
+ "#{text.byteslice(0, [bytes, 0].max).scrub("")}…[TRUNCATED size=#{text.bytesize}]"
96
+ end
97
+
98
+ # `CLAVE=VALOR`, `CLAVE: VALOR` o `CLAVE => VALOR` en texto, con una clave que {#sensitive?} taparía: la misma
99
+ # regla (lista del servicio exacta, o el default por "contiene" salvo `unfiltered_keys`), escrita como regex
100
+ # para buscarla en el texto. La clave puede ir entre comillas o corchetes (`"password" => x`,
101
+ # `user[password]=x`), empieza en el borde de una palabra y se toma entera sin volver atrás (`*+`), así el costo
102
+ # es lineal.
103
+ #
104
+ # Se compila una vez por combinación de listas: compilarla en cada línea costaba 0,02 ms (medido).
105
+ #
106
+ # @param keys [Set<String>] `filtered_keys`, en minúsculas.
107
+ # @param unfiltered [Set<String>] `unfiltered_keys`, en minúsculas.
108
+ # @return [Regexp]
109
+ def self.key_value_regex(keys, unfiltered)
110
+ @key_value_regexes ||= {}
111
+ @key_value_regexes[[keys.sort, unfiltered.sort]] ||= build_key_value_regex(keys, unfiltered)
112
+ end
113
+
114
+ def self.build_key_value_regex(keys, unfiltered_keys)
115
+ word_end = "(?![\\w.-])"
116
+ exact = ->(names) { names.map { |name| Regexp.escape(name) }.join("|") }
117
+ by_service = keys.empty? ? nil : "(?:#{exact.call(keys)})#{word_end}"
118
+ unfiltered = unfiltered_keys.empty? ? "" : "(?!(?:#{exact.call(unfiltered_keys)})#{word_end})"
119
+ by_default = "#{unfiltered}(?=[\\w.-]*?(?:#{DEFAULT_SENSITIVE.source}))\\w[\\w.-]*+"
120
+ key = [by_service, by_default].compact.join("|")
121
+ Regexp.new(<<~REGEX, Regexp::IGNORECASE | Regexp::EXTENDED)
122
+ (?<![\\w.-])(?<key>#{key})(?<close>["'\\]]?)
123
+ (?<sep>\\s*(?:=>|=|:)\\s*)
124
+ #{SENSITIVE_VALUE}
125
+ REGEX
126
+ end
127
+ private_class_method :build_key_value_regex
128
+
129
+ # @param key [String, Symbol]
130
+ # @return [Boolean] true si la clave se tapa: por nombre exacto en la lista del servicio, o por el default,
131
+ # salvo que el servicio la haya destapado con `unfiltered_keys`.
132
+ def sensitive?(key)
133
+ name = key.to_s.downcase
134
+ return true if @keys.include?(name)
135
+ return false if @unfiltered.include?(name)
136
+
137
+ name.match?(DEFAULT_SENSITIVE)
138
+ end
139
+
140
+ # Tapa `CLAVE=VALOR` y credenciales de `Authorization` dentro de un string.
141
+ #
142
+ # @param text [String]
143
+ # @return [String]
144
+ def sanitize_text(text)
145
+ text = text.scrub
146
+ assignment = text.match(ASSIGNMENT)
147
+ return "#{assignment[:key]}=#{FILTERED}" if assignment && sensitive?(assignment[:key])
148
+
149
+ # Cada pasada se saltea si su ancla no está: buscar un literal es mucho más barato que recorrer la regex.
150
+ text = text.gsub(AUTH_SCHEME) { "#{Regexp.last_match[:scheme]} #{FILTERED}" } if text.match?(AUTH_ANCHOR)
151
+ text = text.gsub(URL_CREDENTIALS) { "#{Regexp.last_match[:prefix]}#{FILTERED}@" } if text.include?("://")
152
+ mask_key_values(text)
153
+ end
154
+
155
+ private
156
+
157
+ # Tapa el valor de cada `CLAVE=VALOR` con clave sensible. La regex sólo coincide con claves sensibles, así que
158
+ # una clave que no lo es no consume nada y no se come el par que la sigue (`failed: token: x`).
159
+ def mask_key_values(text)
160
+ return text unless text.match?(KV_ANCHOR)
161
+
162
+ text.gsub(@key_value) do
163
+ match = Regexp.last_match
164
+ "#{match[:key]}#{match[:close]}#{match[:sep]}#{FILTERED}"
165
+ end
166
+ end
167
+
168
+ def walk(obj, key, depth)
169
+ @nodes += 1
170
+ return "[TRUNCATED nodes]" if @nodes > MAX_NODES
171
+ return "[TRUNCATED depth]" if depth > MAX_DEPTH
172
+
173
+ case obj
174
+ when Hash then walk_hash(obj, depth)
175
+ when Array then walk_array(obj, key, depth)
176
+ when String then walk_string(obj, key, depth)
177
+ when Symbol then walk_string(obj.to_s, key, depth)
178
+ when Numeric, TrueClass, FalseClass, NilClass then obj
179
+ else walk_object(obj, key, depth)
180
+ end
181
+ end
182
+
183
+ def walk_hash(hash, depth)
184
+ hash.each_with_object({}) do |(key, value), result|
185
+ result[key] = sensitive?(key) ? FILTERED : walk(value, key, depth + 1)
186
+ end
187
+ end
188
+
189
+ def walk_array(array, key, depth)
190
+ max = @config.max_array_items
191
+ items = array.first(max).map { |element| walk(element, key, depth + 1) }
192
+ items << "[TRUNCATED count=#{array.size}]" if array.size > max
193
+ items
194
+ end
195
+
196
+ # Un string de más de {Configuration#max_traverse_bytes} no se recorre: se reemplaza entero, salvo el
197
+ # diagnóstico, que se recorta por el principio y se tapa.
198
+ def walk_string(str, key, depth)
199
+ str = to_utf8(str)
200
+ if str.bytesize > @config.max_traverse_bytes
201
+ return "[TOO_LARGE size=#{str.bytesize}]" unless untruncated?(key)
202
+
203
+ return sanitize_text(self.class.truncate_bytes(str, @config.max_traverse_bytes))
204
+ end
205
+
206
+ embedded = parse_json(str)
207
+ return JSON.generate(walk(embedded, key, depth + 1)) unless embedded.nil?
208
+
209
+ truncate(sanitize_text(str), key)
210
+ end
211
+
212
+ # Objetos que no son Hash/Array/String: se pasan a su forma de datos y se recorren igual.
213
+ def walk_object(obj, key, depth)
214
+ data = if obj.respond_to?(:to_unsafe_h) then obj.to_unsafe_h
215
+ elsif obj.is_a?(Struct) then obj.to_h
216
+ elsif obj.respond_to?(:as_json) then obj.as_json
217
+ else obj.to_s
218
+ end
219
+ walk(data, key, depth + 1)
220
+ end
221
+
222
+ # Un string en otra codificación se pasa a UTF-8 (lo que no se puede convertir queda como `?`): si no, recortarlo
223
+ # o escribirlo junto al resto de la línea levanta `Encoding::CompatibilityError`.
224
+ def to_utf8(str)
225
+ return str if str.encoding == Encoding::UTF_8
226
+
227
+ str.encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: "?")
228
+ end
229
+
230
+ # @return [Hash, Array, nil] el JSON de un string que lo es entero; nil si no.
231
+ def parse_json(str)
232
+ stripped = str.lstrip
233
+ return unless stripped.start_with?("{", "[")
234
+
235
+ parsed = JSON.parse(stripped)
236
+ parsed.is_a?(Hash) || parsed.is_a?(Array) ? parsed : nil
237
+ rescue JSON::ParserError
238
+ nil
239
+ end
240
+
241
+ def truncate(str, key)
242
+ return str if untruncated?(key)
243
+
244
+ max = @config.max_value_chars
245
+ str.length > max ? "#{str[0, max]}…[TRUNCATED size=#{str.length}]" : str
246
+ end
247
+
248
+ # El mensaje entero (clave nil) tampoco se recorta acá: lo limita el tope de línea.
249
+ def untruncated?(key)
250
+ key.nil? || DIAGNOSTIC_KEYS.include?(key.to_s)
251
+ end
252
+ end
253
+ end
@@ -112,8 +112,6 @@ module ExisRay
112
112
  server_address: extract_server_address(headers["HTTP_HOST"])
113
113
  }
114
114
 
115
- data[:path] = payload[:path] if ExisRay.configuration.emit_legacy_path_key
116
-
117
115
  data.merge!(exception_data)
118
116
  data.merge!(self.class.extra_fields(event))
119
117
  data.compact
@@ -131,32 +129,18 @@ module ExisRay
131
129
  end
132
130
 
133
131
  # Extrae los datos de excepción para logs OTel.
134
- # Siempre emite `exception.type`/`exception.message`/`exception.stacktrace` (OTel v1.0).
135
- # Emite además los campos legacy (`error_class`/`error_message`) cuando
136
- # `ExisRay.configuration.emit_legacy_exception_keys` es `true` (default durante la
137
- # ventana de transición). Setear a `false` cuando los consumers hayan migrado.
132
+ # Emite `exception.type`/`exception.message`/`exception.stacktrace` (OTel v1.0).
138
133
  #
139
134
  # El stacktrace se toma de `payload[:exception_object]` (expuesto por Rails), no
140
135
  # de `payload[:exception]` que es solo `[class_name, message]`.
141
136
  #
142
137
  # @param payload [Hash] Payload completo del notification de Rails.
143
- # @return [Hash] Campos exception.* (y error_class/error_message si el flag está activo).
138
+ # @return [Hash] Campos exception.*.
144
139
  def extract_exception_data(payload)
145
140
  exception_info = payload[:exception]
146
141
  return {} unless exception_info
147
142
 
148
- exception_class = exception_info.first
149
- exception_message = exception_info.last
150
-
151
- data = {
152
- "exception.type": exception_class,
153
- "exception.message": exception_message
154
- }
155
-
156
- if ExisRay.configuration.emit_legacy_exception_keys
157
- data[:error_class] = exception_class
158
- data[:error_message] = exception_message
159
- end
143
+ data = { "exception.type": exception_info.first, "exception.message": exception_info.last }
160
144
 
161
145
  exception_object = payload[:exception_object]
162
146
  if exception_object.respond_to?(:backtrace) && exception_object.backtrace
@@ -53,9 +53,9 @@ module ExisRay
53
53
  end
54
54
 
55
55
  # Aplicamos el formateador JSON globalmente al logger ya instanciado de Rails
56
- if ExisRay.configuration.json_logs? && Rails.logger
57
- Rails.logger.formatter = ExisRay::JsonFormatter.new
56
+ ExisRay.install_log_formatter(Rails.logger)
58
57
 
58
+ if ExisRay.configuration.json_logs? && Rails.logger
59
59
  # Activamos nuestro LogSubscriber HTTP y suprimimos los de Rails por defecto.
60
60
  # Reemplaza Lograge, compatible con Rails 6, 7 y 8.
61
61
  require "exis_ray/log_subscriber"
@@ -118,7 +118,7 @@ module ExisRay
118
118
  end
119
119
  end
120
120
 
121
- ::Sidekiq.logger.formatter = ExisRay::JsonFormatter.new if ExisRay.configuration.json_logs? && ::Sidekiq.logger
121
+ ExisRay.install_log_formatter(::Sidekiq.logger)
122
122
  log_boot("component=exis_ray event=sidekiq_instrumented")
123
123
  end
124
124
  end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "delegate"
4
+ require "logger"
5
+
6
+ module ExisRay
7
+ # Formatter del modo texto (ADR-131): envuelve el formatter que ya tiene el logger (el de Rails, el de
8
+ # Sidekiq) y le pasa el mensaje tapado y limitado. El formato de salida es el del formatter envuelto, así
9
+ # que lo que ven las apps no cambia, salvo lo tapado o recortado.
10
+ #
11
+ # Todo lo demás (tags de `ActiveSupport::TaggedLogging`, por ejemplo) se delega al formatter envuelto.
12
+ class SanitizingFormatter < SimpleDelegator
13
+ # Envuelve el formatter de cada logger (y de cada logger de un `ActiveSupport::BroadcastLogger`), una sola
14
+ # vez.
15
+ #
16
+ # @param logger [Logger, nil]
17
+ # @return [void]
18
+ def self.install(logger)
19
+ return if logger.nil?
20
+
21
+ targets = logger.respond_to?(:broadcasts) ? logger.broadcasts : [logger]
22
+ targets.each do |target|
23
+ next if target.formatter.is_a?(self)
24
+
25
+ target.formatter = new(target.formatter || ::Logger::Formatter.new)
26
+ end
27
+ end
28
+
29
+ # @return [String] la línea del formatter envuelto, con el mensaje tapado y limitado.
30
+ def call(severity, time, progname, msg)
31
+ limit(__getobj__.call(severity, time, progname, sanitize(msg)))
32
+ rescue StandardError, SystemStackError => e
33
+ __getobj__.call(severity, time, progname, "filter_error=#{e.class.name}")
34
+ end
35
+
36
+ # `ActiveSupport::TaggedLogging#tagged` sin bloque clona el formatter. El `initialize_clone` de `Delegator` le
37
+ # pasa `freeze:` al clon del envuelto, y `Proc#clone` no lo acepta (Ruby 3.4): con un formatter `proc`, el
38
+ # `tagged` de la app levantaba `ArgumentError`.
39
+ #
40
+ # @param other [SanitizingFormatter]
41
+ # @return [void]
42
+ def initialize_clone(other, **)
43
+ __setobj__(other.__getobj__.clone)
44
+ end
45
+
46
+ private
47
+
48
+ def sanitize(msg)
49
+ sanitizer = ExisRay::LogSanitizer.new(ExisRay.configuration)
50
+ msg = "#{msg.message} (#{msg.class})\n#{(msg.backtrace || []).join("\n")}" if msg.is_a?(Exception)
51
+ sanitizer.call(msg)
52
+ end
53
+
54
+ # Tope de {Configuration#max_line_bytes} sobre la línea que escribió el formatter envuelto (con su prefijo):
55
+ # la recorta en un borde UTF-8 válido y conserva el salto de línea.
56
+ def limit(line)
57
+ max = ExisRay.configuration.max_line_bytes
58
+ return line if !line.is_a?(String) || line.bytesize <= max
59
+
60
+ # Los 64 bytes son lugar para lo que se agrega después del recorte: el marcador
61
+ # `…[TRUNCATED size=N]` (40 bytes con un N de 20 dígitos) y el salto de línea.
62
+ "#{LogSanitizer.truncate_bytes(line, max - 64)}#{"\n" if line.end_with?("\n")}"
63
+ end
64
+ end
65
+ end