libo11y 0.2.0 → 0.3.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.
Files changed (38) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +170 -21
  3. data/README.md +77 -8
  4. data/lib/libo11y/{proc.rb → child_process.rb} +12 -2
  5. data/lib/libo11y/db.rb +22 -10
  6. data/lib/libo11y/detached.rb +241 -29
  7. data/lib/libo11y/http_client.rb +48 -15
  8. data/lib/libo11y/internal/bridges.rb +3553 -255
  9. data/lib/libo11y/internal/endpoint.rb +7 -1
  10. data/lib/libo11y/internal/env.rb +177 -59
  11. data/lib/libo11y/internal/error_type.rb +17 -0
  12. data/lib/libo11y/internal/histogram_buckets.rb +42 -0
  13. data/lib/libo11y/internal/http_common.rb +2 -0
  14. data/lib/libo11y/internal/identity.rb +10 -1
  15. data/lib/libo11y/internal/injected.rb +178 -0
  16. data/lib/libo11y/internal/logging_device.rb +141 -32
  17. data/lib/libo11y/internal/path_match.rb +148 -0
  18. data/lib/libo11y/internal/pii.rb +185 -65
  19. data/lib/libo11y/internal/pipeline.rb +141 -34
  20. data/lib/libo11y/internal/policy.rb +556 -52
  21. data/lib/libo11y/internal/propagators.rb +29 -6
  22. data/lib/libo11y/internal/quiet_inspect.rb +20 -0
  23. data/lib/libo11y/internal/resource.rb +187 -52
  24. data/lib/libo11y/internal/sdk_load.rb +64 -0
  25. data/lib/libo11y/internal/sql_text.rb +365 -67
  26. data/lib/libo11y/internal/summary.rb +2 -1
  27. data/lib/libo11y/options.rb +159 -1
  28. data/lib/libo11y/rack.rb +257 -44
  29. data/lib/libo11y/record.rb +70 -7
  30. data/lib/libo11y/redact.rb +87 -21
  31. data/lib/libo11y/signals.rb +70 -29
  32. data/lib/libo11y/spec/app_registry.rb +97 -61
  33. data/lib/libo11y/spec/yaml_v3.rb +179 -111
  34. data/lib/libo11y/telemetry.rb +315 -53
  35. data/lib/libo11y/testing.rb +31 -19
  36. data/lib/libo11y/version.rb +1 -1
  37. data/lib/libo11y.rb +1 -1
  38. metadata +94 -39
@@ -42,9 +42,23 @@ module Libo11y
42
42
  class SensitivityPolicy
43
43
  RULE_SECRET = "secret_attribute"
44
44
  RULE_PII = "pii_attribute"
45
+ INT64_MIN = -(1 << 63)
46
+ INT64_MAX = (1 << 63) - 1
45
47
 
46
48
  attr_reader :pii_mode
47
49
 
50
+ def self.utf8_safe(str)
51
+ LogCapture.utf8_safe(str)
52
+ end
53
+
54
+ def self.normalize_key(raw_key)
55
+ LogCapture.utf8_safe(raw_key.to_s)
56
+ end
57
+
58
+ def self.otel_safe_flat_value(value, snapshot: false)
59
+ LogCapture.otel_safe_flat_value(value, snapshot: snapshot)
60
+ end
61
+
48
62
  # Loads the registries of the app_registries option and returns the
49
63
  # sensitivity class of each key they declare. A source is a compiled
50
64
  # registry, a Pathname, or a String. A String of one line is a path,
@@ -91,7 +105,12 @@ module Libo11y
91
105
 
92
106
  def initialize(pii_mode: PIIMode::DROP, pii_hash_key: nil, app_classes: nil, recorder: nil)
93
107
  mode = pii_mode.is_a?(Symbol) ? pii_mode : pii_mode.to_s.to_sym
94
- raise Error, "o11y: invalid pii_mode #{pii_mode.inspect}" unless PIIMode::ALL.include?(mode)
108
+ raise ArgumentError, "libo11y: pii_mode must be one of #{PIIMode::ALL.join(", ")}, got #{pii_mode.inspect}" unless PIIMode::ALL.include?(mode)
109
+ # The class and not the value, which is a secret.
110
+ unless pii_hash_key.nil? || pii_hash_key.is_a?(String)
111
+ raise ArgumentError,
112
+ "libo11y: pii_hash_key must be a String, got #{pii_hash_key.class}"
113
+ end
95
114
 
96
115
  key_bytes = pii_hash_key.nil? ? "".b : pii_hash_key.b
97
116
  raise PIIHashKey if mode == PIIMode::HASH && key_bytes.bytesize < PII::MIN_PII_HASH_KEY_LEN
@@ -102,6 +121,15 @@ module Libo11y
102
121
  @recorder = recorder
103
122
  end
104
123
 
124
+ # The hash key is a secret, so inspecting the policy does not show it.
125
+ def inspect
126
+ "#<#{self.class.name} pii_mode=#{@pii_mode.inspect} app_keys=#{@app.size}>"
127
+ end
128
+
129
+ def pretty_print(printer)
130
+ printer.text(inspect)
131
+ end
132
+
105
133
  def silent
106
134
  SensitivityPolicy.new(pii_mode: @pii_mode, pii_hash_key: @key, app_classes: @app, recorder: nil)
107
135
  end
@@ -140,8 +168,8 @@ module Libo11y
140
168
  true
141
169
  end
142
170
 
143
- def tokenize(value)
144
- PII.token(@key, value)
171
+ def tokenize(value, floor: :passthrough)
172
+ PII.token(@key, value, floor: floor)
145
173
  end
146
174
 
147
175
  def classify_flat(signal, attrs)
@@ -150,17 +178,18 @@ module Libo11y
150
178
  changed = false
151
179
  out = {}
152
180
  attrs.each do |raw_k, raw_v|
153
- k = raw_k.to_s
154
- v = render(raw_v)
155
- changed = true unless v.equal?(raw_v)
181
+ k = self.class.normalize_key(raw_k)
182
+ changed = true unless k.equal?(raw_k)
156
183
  act = decide(signal, k)
157
184
  if act == :drop
158
185
  changed = true
159
186
  next
160
187
  elsif act == :rewrite
161
188
  changed = true
162
- out[k] = tokenize(v)
189
+ out[k] = tokenize(raw_v)
163
190
  else
191
+ v = render(raw_v)
192
+ changed = true unless v.equal?(raw_v)
164
193
  out[k] = v
165
194
  end
166
195
  end
@@ -172,10 +201,10 @@ module Libo11y
172
201
 
173
202
  out = {}
174
203
  attrs.each do |raw_k, raw_v|
175
- k = raw_k.to_s
204
+ k = self.class.normalize_key(raw_k)
176
205
  next unless metric_keep?(k)
177
206
 
178
- out[k] = render(raw_v)
207
+ out[k] = self.class.otel_safe_flat_value(render(raw_v), snapshot: true)
179
208
  end
180
209
  out
181
210
  end
@@ -189,26 +218,26 @@ module Libo11y
189
218
  # entered. A reference back into the value being walked, the attributes
190
219
  # themselves included, is cut. What the walk did not examine is dropped,
191
220
  # and so is a Hash or Array that classification emptied.
192
- def classify_log_attributes(attrs, replacer: nil)
221
+ def classify_log_attributes(attrs, replacer: nil, seen: nil, key_origins: nil)
193
222
  return {} if attrs.nil? || attrs.empty?
194
223
 
195
- walk = LogWalk.new(PII::MAX_COMPOSITE_NODES, { attrs => true }.compare_by_identity, replacer)
196
- walk_hash(attrs, [], walk).first
224
+ # Set identity comparison before inserting attrs so a value whose
225
+ # #hash raises cannot abort classification before the walk drops it.
226
+ active = {}.compare_by_identity
227
+ active[attrs] = true
228
+ if seen.is_a?(Array)
229
+ seen.each { |origin| active[origin] = true unless origin.nil? }
230
+ elsif !seen.nil?
231
+ active[seen] = true
232
+ end
233
+ walk = LogCapture::Walk.new(
234
+ PII::MAX_COMPOSITE_NODES, active, replacer, key_origins, PII::MAX_COMPOSITE_NODES, {}.compare_by_identity
235
+ )
236
+ walk_hash(attrs, [], walk, :passthrough).first
197
237
  end
198
238
 
199
239
  private
200
240
 
201
- LogWalk = Struct.new(:budget, :active, :replacer) do
202
- # Takes one node from the budget and reports whether any remained.
203
- def spend?
204
- return false if budget <= 0
205
-
206
- self.budget -= 1
207
- true
208
- end
209
- end
210
- private_constant :LogWalk
211
-
212
241
  # Renders a Secret, Masked or Fields value, also inside a Hash or Array.
213
242
  def render(value)
214
243
  case value
@@ -220,51 +249,89 @@ module Libo11y
220
249
 
221
250
  # Classifies one Hash's members. Returns what survives, and whether any
222
251
  # member was dropped.
223
- def walk_hash(mapping, groups, walk)
252
+ def walk_hash(mapping, groups, walk, floor = :passthrough)
224
253
  out = {}
225
254
  changed = false
226
255
  mapping.each do |raw_k, raw_v|
227
256
  return [out, true] unless walk.spend? # the budget is spent: drop the remaining members
228
257
 
229
- k = raw_k.to_s
230
- # Capture-time redaction first, so the replacer never sees a raw Secret or Masked.
231
- val = Redact.redactable?(raw_v) ? Redact.render(raw_v) : raw_v
258
+ k = self.class.normalize_key(raw_k)
259
+ origin = groups.empty? ? walk.key_origins&.[](k) : nil
260
+ changed = walk_member(out, groups, walk, key: k, raw_v: raw_v, floor: floor, origin: origin) || changed
261
+ end
262
+ [out, changed]
263
+ end
264
+
265
+ # Walks a Redact::Fields object lazily under the shared depth and node
266
+ # budget, spending one node before invoking each field getter.
267
+ def walk_fields(fields, groups, walk, floor)
268
+ out = {}
269
+ changed = false
270
+ Redact.field_specs(fields, floor).each do |name, next_floor|
271
+ return [out, true] unless walk.spend?
272
+
273
+ raw = next_floor == :redact ? Redact::REDACTED : Redact.read_field(fields, name)
274
+ changed = walk_member(out, groups, walk, key: self.class.normalize_key(name), raw_v: raw, floor: next_floor, origin: nil) || changed
275
+ end
276
+ [out, changed]
277
+ end
278
+
279
+ def walk_member(out, groups, walk, key:, raw_v:, floor:, origin:)
280
+ with_origin(walk.active, origin) do
281
+ val, effective_floor = LogCapture.capture_member(raw_v, floor, walk, groups.length + 1)
282
+ return true if val.equal?(LogCapture::DROPPED)
232
283
 
233
284
  if walk.replacer
234
- replaced = walk.replacer.call(groups, k, val)
235
- k, val = replaced
236
- k = k.to_s
237
- if replaced.nil? || k.empty?
238
- changed = true
239
- next
240
- end
285
+ replaced = LogCapture.apply_replacer(walk.replacer, groups, key, val)
286
+ return true if replaced.nil?
287
+
288
+ key, val = replaced
289
+ return true if key.empty?
241
290
  end
291
+ key = key.dup.freeze unless key.frozen?
242
292
 
243
- case decide(Spec::Signal::LOGS, (groups + [k]).join("."))
293
+ case decide(Spec::Signal::LOGS, (groups + [key]).join("."))
244
294
  when :drop
245
- changed = true
295
+ true
246
296
  when :rewrite
247
- out[k] = tokenize(val)
297
+ out[key] = tokenize(val, floor: effective_floor)
298
+ false
248
299
  else
249
- member, keep, member_changed = walk_value(val, groups + [k], 0, walk)
250
- changed ||= member_changed
251
- out[k] = member if keep
300
+ member, keep, member_changed = walk_value(val, groups + [key], 0, walk, effective_floor)
301
+ out[key] = member if keep
302
+ member_changed
252
303
  end
253
304
  end
254
- [out, changed]
305
+ end
306
+
307
+ def with_origin(active, origin)
308
+ return yield if origin.nil? || active.key?(origin)
309
+
310
+ active[origin] = true
311
+ begin
312
+ yield
313
+ ensure
314
+ active.delete(origin)
315
+ end
255
316
  end
256
317
 
257
318
  # Classifies one value held under the effective key path. Returns the
258
319
  # classified value, whether to keep it, and whether classification
259
- # dropped anything. depth counts Array nesting, and a Hash member starts
260
- # again at zero, so a Hash is bounded by the length of its effective key
261
- # and an Array by its nesting.
262
- def walk_value(value, path, depth, walk)
263
- value = Redact.render(value) if Redact.redactable?(value)
320
+ # dropped anything. depth counts Array nesting, and a Hash or Fields
321
+ # member starts again at zero, so a Hash/Fields is bounded by the length
322
+ # of its effective key and an Array by its nesting.
323
+ def walk_value(value, path, depth, walk, floor = :passthrough)
324
+ return [Redact::REDACTED, true, false] if floor == :redact
325
+
264
326
  case value
265
- when nil, true, false, Integer, Float, String then return [value, true, false]
266
- when Hash, Array then nil
267
- else return [value.to_s, true, false]
327
+ when nil then return [nil, true, false]
328
+ when Redact::Secret then return [Redact::REDACTED, true, false]
329
+ when Redact::Masked then return [value.to_s, true, false]
330
+ when true, false, Integer, Float, String
331
+ return [floor == :mask ? Redact.mask_string(value) : value, true, false]
332
+ when Hash, Array, Redact::Fields then nil
333
+ else
334
+ return [floor == :mask ? Redact.mask_string(value) : value.to_s, true, false]
268
335
  end
269
336
 
270
337
  if depth >= PII::MAX_COMPOSITE_DEPTH || path.length > PII::MAX_COMPOSITE_DEPTH || !walk.spend? || walk.active.key?(value)
@@ -273,14 +340,18 @@ module Libo11y
273
340
 
274
341
  walk.active[value] = true
275
342
  begin
276
- out, changed = value.is_a?(Hash) ? walk_hash(value, path, walk) : walk_array(value, path, depth, walk)
343
+ out, changed = case value
344
+ when Hash then walk_hash(value, path, walk, floor)
345
+ when Redact::Fields then walk_fields(value, path, walk, floor)
346
+ else walk_array(value, path, depth, walk, floor)
347
+ end
277
348
  [out, !out.empty? || !changed, changed]
278
349
  ensure
279
350
  walk.active.delete(value)
280
351
  end
281
352
  end
282
353
 
283
- def walk_array(list, path, depth, walk)
354
+ def walk_array(list, path, depth, walk, floor = :passthrough)
284
355
  kept = []
285
356
  changed = false
286
357
  list.each do |el|
@@ -288,12 +359,445 @@ module Libo11y
288
359
  changed = true # the budget is spent: drop the remaining elements
289
360
  break
290
361
  end
291
- member, keep, member_changed = walk_value(el, path, depth + 1, walk)
362
+ member, keep, member_changed = walk_value(el, path, depth + 1, walk, floor)
292
363
  changed ||= member_changed
293
364
  kept << member if keep
294
365
  end
295
366
  [kept, changed]
296
367
  end
297
368
  end
369
+
370
+ # Capture-time redaction helpers used by SensitivityPolicy before
371
+ # attr_replacer runs on log attributes.
372
+ module LogCapture
373
+ DROPPED = Object.new.freeze
374
+ Walk = Struct.new(:budget, :active, :replacer, :key_origins, :capture_budget, :captured) do
375
+ def spend?
376
+ return false if budget <= 0
377
+
378
+ self.budget -= 1
379
+ true
380
+ end
381
+
382
+ def spend_capture?
383
+ return false if capture_budget <= 0
384
+
385
+ self.capture_budget -= 1
386
+ true
387
+ end
388
+ end
389
+
390
+ module_function
391
+
392
+ # Invokes attr_replacer with independent copies of the group path and key,
393
+ # normalizing the returned key and failing closed on any exception or
394
+ # malformed return value without exposing raw exception messages.
395
+ def apply_replacer(replacer, groups, key, value)
396
+ replaced = replacer.call(groups.map(&:dup), key.dup, value)
397
+ return nil if replaced.nil?
398
+
399
+ unless replaced.is_a?(Array) && replaced.length == 2
400
+ OpenTelemetry.handle_error(message: "libo11y: attr_replacer returned #{replaced.class}, expected [key, value] or nil")
401
+ return nil
402
+ end
403
+
404
+ new_key, new_val = replaced
405
+ [utf8_safe(new_key.to_s), new_val]
406
+ rescue StandardError => e
407
+ OpenTelemetry.handle_error(message: "libo11y: attr_replacer raised #{e.class}")
408
+ nil
409
+ end
410
+
411
+ # Normalizes any String to valid UTF-8 so encoding differences (such as
412
+ # UTF-16LE, UTF-7, or BINARY) match the UTF-8 registry tables and never
413
+ # break console JSON or OTLP protobuf encoding. Returns str unchanged
414
+ # when it is already valid UTF-8.
415
+ def utf8_safe(str)
416
+ return str unless str.is_a?(String)
417
+ return str if str.encoding == Encoding::UTF_8 && str.valid_encoding?
418
+ return str.dup.force_encoding(Encoding::UTF_8).scrub if [Encoding::UTF_8, Encoding::BINARY].include?(str.encoding)
419
+
420
+ str.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
421
+ rescue EncodingError
422
+ str.b.force_encoding(Encoding::UTF_8).scrub
423
+ end
424
+
425
+ def otel_safe_attr_map(attrs, snapshot: false)
426
+ OtelSafe.attr_map(attrs, snapshot: snapshot)
427
+ end
428
+
429
+ def otel_safe_flat_value(value, snapshot: false)
430
+ OtelSafe.flat_value(value, snapshot: snapshot)
431
+ end
432
+
433
+ # Applies capture-time redaction before attr_replacer runs, while keeping
434
+ # traversal lazy when no replacer is configured. Whenever capture
435
+ # redaction already resolved the value, the returned floor resets to
436
+ # :passthrough so a Secret under :mask is never double-masked.
437
+ def capture_member(raw_v, floor, walk, next_path_len)
438
+ return [Redact::REDACTED, :passthrough] if floor == :redact || raw_v.is_a?(Redact::Secret)
439
+ return [raw_v.to_s, :passthrough] if raw_v.is_a?(Redact::Masked)
440
+ return [nil, :passthrough] if raw_v.nil?
441
+
442
+ unless raw_v.is_a?(Hash) || raw_v.is_a?(Array) || raw_v.is_a?(Redact::Fields)
443
+ return [floor == :mask ? Redact.mask_string(raw_v) : raw_v, :passthrough]
444
+ end
445
+ return [raw_v, floor] unless walk.replacer
446
+ if floor == :passthrough && walk.captured.key?(raw_v) &&
447
+ !dirty_composite?(raw_v, walk_active: walk.active, path_len: next_path_len)
448
+ return [raw_v, :passthrough]
449
+ end
450
+
451
+ captured, keep = capture_composite(raw_v, floor: floor, path_len: next_path_len, depth: 0, walk: walk, seen: {}.compare_by_identity)
452
+ keep ? [captured, :passthrough] : [DROPPED, :passthrough]
453
+ end
454
+
455
+ # Read-only bounded check (spending zero capture budget) for whether a
456
+ # parent attr_replacer mutated a captured composite in place to insert a
457
+ # Redact wrapper, a cycle, or a structure past the composite limits.
458
+ def dirty_composite?(value, walk_active:, path_len:, depth: 0, budget: [PII::MAX_COMPOSITE_NODES], seen: {}.compare_by_identity)
459
+ return true if depth >= PII::MAX_COMPOSITE_DEPTH || path_len > PII::MAX_COMPOSITE_DEPTH
460
+ return true if walk_active.key?(value) || seen.key?(value)
461
+
462
+ budget[0] -= 1
463
+ return true if budget[0].negative?
464
+
465
+ seen[value] = true
466
+ begin
467
+ dirty_children?(value, walk_active: walk_active, path_len: path_len, depth: depth, budget: budget, seen: seen)
468
+ ensure
469
+ seen.delete(value)
470
+ end
471
+ end
472
+
473
+ def dirty_children?(value, walk_active:, path_len:, depth:, budget:, seen:)
474
+ if value.is_a?(Hash)
475
+ next_path = path_len + 1
476
+ value.each_value do |child|
477
+ budget[0] -= 1
478
+ return true if budget[0].negative? || Redact.redactable?(child)
479
+ next unless child.is_a?(Hash) || child.is_a?(Array)
480
+ return true if dirty_composite?(child, walk_active: walk_active, path_len: next_path, depth: 0, budget: budget, seen: seen)
481
+ end
482
+ else
483
+ next_depth = depth + 1
484
+ value.each do |child|
485
+ budget[0] -= 1
486
+ return true if budget[0].negative? || Redact.redactable?(child)
487
+ next unless child.is_a?(Hash) || child.is_a?(Array)
488
+ return true if dirty_composite?(child, walk_active: walk_active, path_len: path_len, depth: next_depth, budget: budget, seen: seen)
489
+ end
490
+ end
491
+ false
492
+ end
493
+
494
+ # Produces a bounded, cycle-safe capture-redacted copy of a composite
495
+ # before handing it to attr_replacer so the replacer cannot see raw
496
+ # Secret, Masked, or tagged Redact::Fields values.
497
+ def capture_composite(value, floor:, path_len:, depth:, walk:, seen:)
498
+ return [Redact::REDACTED, true] if floor == :redact
499
+
500
+ case value
501
+ when nil then return [nil, true]
502
+ when Redact::Secret then return [Redact::REDACTED, true]
503
+ when Redact::Masked then return [value.to_s, true]
504
+ when Hash, Array, Redact::Fields then nil
505
+ else
506
+ return [floor == :mask ? Redact.mask_string(value) : value, true]
507
+ end
508
+
509
+ if depth >= PII::MAX_COMPOSITE_DEPTH || path_len > PII::MAX_COMPOSITE_DEPTH ||
510
+ !walk.spend_capture? || walk.active.key?(value) || seen.key?(value)
511
+ return [nil, false]
512
+ end
513
+
514
+ seen[value] = true
515
+ begin
516
+ out, changed = case value
517
+ when Hash then capture_hash(value, floor: floor, path_len: path_len, walk: walk, seen: seen)
518
+ when Redact::Fields then capture_fields(value, floor: floor, path_len: path_len, walk: walk, seen: seen)
519
+ else capture_array(value, floor: floor, path_len: path_len, depth: depth, walk: walk, seen: seen)
520
+ end
521
+ keep = !out.empty? || !changed
522
+ walk.captured[out] = true if keep
523
+ [out, keep]
524
+ ensure
525
+ seen.delete(value)
526
+ end
527
+ end
528
+
529
+ def capture_hash(mapping, floor:, path_len:, walk:, seen:)
530
+ out = {}
531
+ changed = false
532
+ mapping.each do |raw_k, raw_v|
533
+ return [out, true] unless walk.spend_capture?
534
+
535
+ member, keep = capture_composite(raw_v, floor: floor, path_len: path_len + 1, depth: 0, walk: walk, seen: seen)
536
+ if keep
537
+ out[SensitivityPolicy.normalize_key(raw_k)] = member
538
+ else
539
+ changed = true
540
+ end
541
+ end
542
+ [out, changed]
543
+ end
544
+
545
+ def capture_fields(fields, floor:, path_len:, walk:, seen:)
546
+ out = {}
547
+ changed = false
548
+ Redact.field_specs(fields, floor).each do |name, next_floor|
549
+ return [out, true] unless walk.spend_capture?
550
+
551
+ raw = next_floor == :redact ? Redact::REDACTED : Redact.read_field(fields, name)
552
+ member, keep = capture_composite(raw, floor: next_floor, path_len: path_len + 1, depth: 0, walk: walk, seen: seen)
553
+ if keep
554
+ out[SensitivityPolicy.normalize_key(name)] = member
555
+ else
556
+ changed = true
557
+ end
558
+ end
559
+ [out, changed]
560
+ end
561
+
562
+ def capture_array(list, floor:, path_len:, depth:, walk:, seen:)
563
+ kept = []
564
+ changed = false
565
+ list.each do |el|
566
+ unless walk.spend_capture?
567
+ changed = true
568
+ break
569
+ end
570
+ member, keep = capture_composite(el, floor: floor, path_len: path_len, depth: depth + 1, walk: walk, seen: seen)
571
+ if keep
572
+ kept << member
573
+ else
574
+ changed = true
575
+ end
576
+ end
577
+ [kept, changed]
578
+ end
579
+ end
580
+
581
+ # Bounded, cycle-safe OTLP attribute value scrubber with zero allocations
582
+ # on clean shallow inputs and deep snapshotting when snapshot: true.
583
+ module OtelSafe
584
+ MAX_DEPTH = PII::MAX_COMPOSITE_DEPTH
585
+ private_constant :MAX_DEPTH
586
+
587
+ module_function
588
+
589
+ def attr_map(attrs, snapshot: false)
590
+ return attrs unless attrs.is_a?(Hash)
591
+
592
+ budget = attrs.size > 16 ? [PII::MAX_COMPOSITE_NODES] : nil
593
+ prefix_nodes = 0
594
+ out = nil
595
+ attrs.each do |k, v|
596
+ if budget && !spend_budget?(budget)
597
+ out ||= copy_hash_prefix(attrs, k)
598
+ break
599
+ end
600
+ if cycle?(v, attrs, nil, nil)
601
+ out ||= copy_hash_prefix(attrs, k)
602
+ next
603
+ end
604
+ budget = start_budget(prefix_nodes) if budget.nil? && needs_budget?(v)
605
+ nk = k.is_a?(String) ? safe_string(k, snapshot: snapshot) : k
606
+ nv = flat_value(v, nil, attrs, top_level: true, snapshot: snapshot, depth: 0, budget: budget)
607
+ out = update_hash(out, attrs, k, nk, nv) if out || !nk.equal?(k) || !nv.equal?(v)
608
+ prefix_nodes += shallow_weight(v) if budget.nil?
609
+ end
610
+ finalize(out, attrs, snapshot)
611
+ end
612
+
613
+ def flat_value(value, active = nil, root = nil, top_level: true, snapshot: false, depth: 0, budget: nil)
614
+ case value
615
+ when String then safe_string(value, snapshot: snapshot)
616
+ when Integer then safe_integer(value, snapshot: snapshot)
617
+ when Hash then scrub_hash(value, active, root, snapshot: snapshot, depth: depth, budget: budget)
618
+ when Array then scrub_array(value, active, root, top_level: top_level, snapshot: snapshot, depth: depth, budget: budget)
619
+ else value
620
+ end
621
+ end
622
+
623
+ def safe_string(str, snapshot:)
624
+ safe = LogCapture.utf8_safe(str)
625
+ return safe unless snapshot && !safe.frozen?
626
+
627
+ safe.dup.freeze
628
+ end
629
+
630
+ def safe_integer(value, snapshot:)
631
+ return value if value.between?(SensitivityPolicy::INT64_MIN, SensitivityPolicy::INT64_MAX)
632
+
633
+ str = value.to_s
634
+ snapshot ? str.freeze : str
635
+ end
636
+
637
+ def cycle?(node, parent, active, root)
638
+ (node.is_a?(Hash) || node.is_a?(Array)) && (node.equal?(parent) || node.equal?(root) || (!active.nil? && active.key?(node)))
639
+ end
640
+
641
+ # Returns true without allocating when child is large or contains a
642
+ # nested Hash/Array so the top-level caller allocates one shared budget
643
+ # across the entire walk instead of per-subtree budgets.
644
+ def needs_budget?(child)
645
+ if child.is_a?(Array)
646
+ len = child.length
647
+ return true if len > 16
648
+
649
+ idx = 0
650
+ while idx < len
651
+ item = child[idx]
652
+ return true if item.is_a?(Hash) || item.is_a?(Array)
653
+
654
+ idx += 1
655
+ end
656
+ elsif child.is_a?(Hash)
657
+ return true if child.size > 16
658
+
659
+ child.each_value { |item| return true if item.is_a?(Hash) || item.is_a?(Array) }
660
+ end
661
+ false
662
+ end
663
+
664
+ def start_budget(prefix_nodes)
665
+ [PII::MAX_COMPOSITE_NODES - prefix_nodes]
666
+ end
667
+
668
+ def shallow_weight(value)
669
+ if value.is_a?(Array)
670
+ 1 + value.length
671
+ elsif value.is_a?(Hash)
672
+ 1 + value.size
673
+ else
674
+ 1
675
+ end
676
+ end
677
+
678
+ def spend_budget?(budget)
679
+ return true if budget.nil?
680
+
681
+ budget[0] -= 1
682
+ !budget[0].negative?
683
+ end
684
+
685
+ def finalize(copy, original, snapshot)
686
+ return copy.freeze if copy && snapshot
687
+ return copy if copy
688
+ return original.dup.freeze if snapshot && !original.frozen?
689
+
690
+ original
691
+ end
692
+
693
+ def update_hash(out, hash, orig_key, new_key, new_val)
694
+ out ||= copy_hash_prefix(hash, orig_key)
695
+ out[new_key] = new_val
696
+ out
697
+ end
698
+
699
+ def scrub_child(child, parent, active, root, snapshot:, depth:, budget:)
700
+ next_depth = depth + 1
701
+ unless child.is_a?(Hash) || child.is_a?(Array)
702
+ return flat_value(child, active, root, top_level: false, snapshot: snapshot, depth: next_depth, budget: budget)
703
+ end
704
+ return flat_value(child, nil, parent, top_level: false, snapshot: snapshot, depth: next_depth, budget: budget) if active.nil? && root.nil?
705
+
706
+ if active.nil?
707
+ next_active = {}.compare_by_identity
708
+ next_active[root] = true
709
+ next_active[parent] = true
710
+ return flat_value(child, next_active, root, top_level: false, snapshot: snapshot, depth: next_depth, budget: budget)
711
+ end
712
+
713
+ active[parent] = true
714
+ begin
715
+ flat_value(child, active, root, top_level: false, snapshot: snapshot, depth: next_depth, budget: budget)
716
+ ensure
717
+ active.delete(parent)
718
+ end
719
+ end
720
+
721
+ def copy_hash_prefix(hash, stop_key)
722
+ copy = {}
723
+ hash.each do |hk, hv|
724
+ break if hk.equal?(stop_key)
725
+
726
+ copy[hk] = hv
727
+ end
728
+ copy
729
+ end
730
+
731
+ def scrub_hash(hash, active, root, snapshot: false, depth: 0, budget: nil)
732
+ return snapshot ? {}.freeze : {} if depth >= MAX_DEPTH
733
+
734
+ budget ||= [PII::MAX_COMPOSITE_NODES] if depth >= 2 || hash.size > 16
735
+ return snapshot ? {}.freeze : {} unless spend_budget?(budget)
736
+
737
+ prefix_nodes = 1
738
+ out = nil
739
+ hash.each do |k, v|
740
+ unless spend_budget?(budget)
741
+ out ||= copy_hash_prefix(hash, k)
742
+ break
743
+ end
744
+ if cycle?(v, hash, active, root)
745
+ out ||= copy_hash_prefix(hash, k)
746
+ next
747
+ end
748
+ budget = start_budget(prefix_nodes) if budget.nil? && needs_budget?(v)
749
+ nk = k.is_a?(String) ? safe_string(k, snapshot: snapshot) : k
750
+ nv = scrub_child(v, hash, active, root, snapshot: snapshot, depth: depth, budget: budget)
751
+ out = update_hash(out, hash, k, nk, nv) if out || !nk.equal?(k) || !nv.equal?(v)
752
+ prefix_nodes += shallow_weight(v) if budget.nil?
753
+ end
754
+ finalize(out, hash, snapshot)
755
+ end
756
+
757
+ def scrub_array(list, active, root, top_level:, snapshot: false, depth: 0, budget: nil)
758
+ return snapshot ? [].freeze : [] if depth >= MAX_DEPTH
759
+
760
+ budget ||= [PII::MAX_COMPOSITE_NODES] if depth >= 2 || list.length > 16
761
+ return snapshot ? [].freeze : [] unless spend_budget?(budget)
762
+
763
+ mapped = scan_array(list, active, root, top_level: top_level, snapshot: snapshot, depth: depth, budget: budget)
764
+ finalize(mapped, list, snapshot)
765
+ end
766
+
767
+ def scan_array(list, active, root, top_level:, snapshot:, depth:, budget:)
768
+ mapped = nil
769
+ int_coerced = false
770
+ prefix_nodes = 1
771
+ idx = 0
772
+ len = list.length
773
+ while idx < len
774
+ unless spend_budget?(budget)
775
+ mapped ||= list[0, idx]
776
+ break
777
+ end
778
+ elem = list[idx]
779
+ if cycle?(elem, list, active, root)
780
+ mapped ||= list[0, idx]
781
+ else
782
+ budget = start_budget(prefix_nodes) if budget.nil? && needs_budget?(elem)
783
+ next_elem = scrub_child(elem, list, active, root, snapshot: snapshot, depth: depth, budget: budget)
784
+ int_coerced = true if elem.is_a?(Integer) && next_elem.is_a?(String)
785
+ mapped = append_item(mapped, list, idx, next_elem) if mapped || !next_elem.equal?(elem)
786
+ prefix_nodes += shallow_weight(elem) if budget.nil?
787
+ end
788
+ idx += 1
789
+ end
790
+ if top_level && int_coerced && mapped.any?(String) && !mapped.all?(String)
791
+ mapped = mapped.map { |item| safe_string(item.to_s, snapshot: snapshot) }
792
+ end
793
+ mapped
794
+ end
795
+
796
+ def append_item(mapped, list, idx, next_elem)
797
+ mapped ||= list[0, idx]
798
+ mapped << next_elem
799
+ mapped
800
+ end
801
+ end
298
802
  end
299
803
  end