datadog 2.35.0 → 2.37.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 (144) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +85 -1
  3. data/ext/datadog_profiling_native_extension/clock_id_from_mach.c +5 -12
  4. data/ext/datadog_profiling_native_extension/collectors_cpu_and_wall_time_worker.c +71 -31
  5. data/ext/datadog_profiling_native_extension/collectors_discrete_dynamic_sampler.c +1 -1
  6. data/ext/datadog_profiling_native_extension/collectors_idle_sampling_helper.c +18 -4
  7. data/ext/datadog_profiling_native_extension/collectors_stack.c +37 -18
  8. data/ext/datadog_profiling_native_extension/collectors_stack.h +8 -2
  9. data/ext/datadog_profiling_native_extension/collectors_thread_context.c +596 -341
  10. data/ext/datadog_profiling_native_extension/collectors_thread_context.h +11 -7
  11. data/ext/datadog_profiling_native_extension/datadog_ruby_common.c +7 -8
  12. data/ext/datadog_profiling_native_extension/datadog_ruby_common.h +0 -12
  13. data/ext/datadog_profiling_native_extension/extconf.rb +13 -2
  14. data/ext/datadog_profiling_native_extension/gvl_profiling_helper.c +4 -43
  15. data/ext/datadog_profiling_native_extension/gvl_profiling_helper.h +15 -47
  16. data/ext/datadog_profiling_native_extension/heap_recorder.c +44 -26
  17. data/ext/datadog_profiling_native_extension/private_vm_api_access.c +14 -35
  18. data/ext/datadog_profiling_native_extension/profiling.c +41 -4
  19. data/ext/datadog_profiling_native_extension/ruby_helpers.c +40 -34
  20. data/ext/datadog_profiling_native_extension/stack_recorder.c +24 -3
  21. data/ext/datadog_profiling_native_extension/stack_recorder.h +1 -0
  22. data/ext/datadog_profiling_native_extension/unsafe_api_calls_check.h +4 -2
  23. data/ext/libdatadog_api/datadog_ruby_common.c +7 -8
  24. data/ext/libdatadog_api/datadog_ruby_common.h +0 -12
  25. data/ext/libdatadog_api/di.c +76 -0
  26. data/ext/libdatadog_api/extconf.rb +6 -0
  27. data/ext/libdatadog_extconf_helpers.rb +1 -1
  28. data/lib/datadog/ai_guard/api_client.rb +6 -4
  29. data/lib/datadog/appsec/api_security/route_extractor.rb +13 -4
  30. data/lib/datadog/appsec/component.rb +1 -1
  31. data/lib/datadog/appsec/configuration.rb +13 -0
  32. data/lib/datadog/appsec/context.rb +4 -2
  33. data/lib/datadog/appsec/contrib/aws_lambda/waf_addresses.rb +37 -4
  34. data/lib/datadog/appsec/contrib/excon/ssrf_detection_middleware.rb +59 -4
  35. data/lib/datadog/appsec/contrib/faraday/ssrf_detection_middleware.rb +59 -5
  36. data/lib/datadog/appsec/contrib/graphql/gateway/multiplex.rb +64 -19
  37. data/lib/datadog/appsec/contrib/graphql/integration.rb +1 -0
  38. data/lib/datadog/appsec/contrib/rack/buffered_input.rb +83 -0
  39. data/lib/datadog/appsec/contrib/rack/gateway/request.rb +41 -3
  40. data/lib/datadog/appsec/contrib/rack/gateway/watcher.rb +24 -7
  41. data/lib/datadog/appsec/contrib/rack/input_peeker.rb +79 -0
  42. data/lib/datadog/appsec/contrib/rack/request_middleware.rb +21 -0
  43. data/lib/datadog/appsec/contrib/rails/gateway/request.rb +35 -1
  44. data/lib/datadog/appsec/contrib/rails/gateway/watcher.rb +17 -1
  45. data/lib/datadog/appsec/contrib/rest_client/request_ssrf_detection_patch.rb +60 -7
  46. data/lib/datadog/appsec/contrib/sinatra/gateway/watcher.rb +24 -3
  47. data/lib/datadog/appsec/default_header_tags.rb +10 -6
  48. data/lib/datadog/appsec/ext.rb +1 -0
  49. data/lib/datadog/appsec/metrics/collector.rb +18 -1
  50. data/lib/datadog/appsec/metrics/exporter.rb +9 -3
  51. data/lib/datadog/appsec/remote.rb +9 -3
  52. data/lib/datadog/appsec/route_normalizer/rails_route_pattern.rb +176 -0
  53. data/lib/datadog/appsec/route_normalizer/route_pattern.rb +378 -0
  54. data/lib/datadog/appsec/route_normalizer/route_text.rb +57 -0
  55. data/lib/datadog/appsec/route_normalizer.rb +80 -0
  56. data/lib/datadog/appsec/utils/http/body_reader.rb +61 -0
  57. data/lib/datadog/core/configuration/components.rb +83 -2
  58. data/lib/datadog/core/configuration/components_state.rb +6 -1
  59. data/lib/datadog/core/configuration/settings.rb +1 -5
  60. data/lib/datadog/core/configuration/supported_configurations.rb +4 -0
  61. data/lib/datadog/core/evp.rb +11 -0
  62. data/lib/datadog/core/remote/client/capabilities.rb +34 -7
  63. data/lib/datadog/core/remote/component.rb +1 -1
  64. data/lib/datadog/core/telemetry/event/app_started.rb +8 -22
  65. data/lib/datadog/core/utils/at_fork_monkey_patch.rb +1 -1
  66. data/lib/datadog/core/utils/forking.rb +3 -1
  67. data/lib/datadog/core/utils/spawn_monkey_patch.rb +3 -1
  68. data/lib/datadog/core.rb +3 -0
  69. data/lib/datadog/di/base.rb +7 -2
  70. data/lib/datadog/di/code_tracker.rb +5 -2
  71. data/lib/datadog/di/component.rb +110 -36
  72. data/lib/datadog/di/error.rb +10 -0
  73. data/lib/datadog/di/fatal_exceptions.rb +26 -0
  74. data/lib/datadog/di/instrumenter.rb +381 -165
  75. data/lib/datadog/di/probe.rb +14 -0
  76. data/lib/datadog/di/probe_file_loader.rb +8 -3
  77. data/lib/datadog/di/probe_manager.rb +67 -9
  78. data/lib/datadog/di/probe_notification_builder.rb +4 -1
  79. data/lib/datadog/di/probe_notifier_worker.rb +52 -32
  80. data/lib/datadog/di/redactor.rb +16 -1
  81. data/lib/datadog/di/remote.rb +175 -14
  82. data/lib/datadog/di/serializer.rb +12 -5
  83. data/lib/datadog/di/transport/input.rb +8 -4
  84. data/lib/datadog/di.rb +63 -0
  85. data/lib/datadog/error_tracking/collector.rb +2 -1
  86. data/lib/datadog/error_tracking/component.rb +2 -2
  87. data/lib/datadog/kit/appsec/events/v2.rb +60 -2
  88. data/lib/datadog/kit/tracing/method_tracer.rb +4 -1
  89. data/lib/datadog/open_feature/component.rb +29 -6
  90. data/lib/datadog/open_feature/configuration.rb +8 -0
  91. data/lib/datadog/open_feature/ext.rb +2 -0
  92. data/lib/datadog/open_feature/flag_evaluation/aggregator.rb +286 -0
  93. data/lib/datadog/open_feature/flag_evaluation/writer.rb +433 -0
  94. data/lib/datadog/open_feature/hooks/flag_eval_evp_hook.rb +101 -0
  95. data/lib/datadog/open_feature/hooks/{flag_eval_hook.rb → flag_eval_metrics_hook.rb} +1 -1
  96. data/lib/datadog/open_feature/native_evaluator.rb +22 -0
  97. data/lib/datadog/open_feature/provider.rb +59 -27
  98. data/lib/datadog/open_feature/transport.rb +55 -1
  99. data/lib/datadog/opentelemetry/sdk/logs_exporter.rb +5 -12
  100. data/lib/datadog/opentelemetry/sdk/metrics_exporter.rb +4 -11
  101. data/lib/datadog/opentelemetry/sdk/propagator.rb +9 -3
  102. data/lib/datadog/opentelemetry/sdk/span_processor.rb +4 -1
  103. data/lib/datadog/opentelemetry/sdk.rb +19 -0
  104. data/lib/datadog/profiling/collectors/cpu_and_wall_time_worker.rb +1 -1
  105. data/lib/datadog/profiling/collectors/idle_sampling_helper.rb +5 -3
  106. data/lib/datadog/profiling/collectors/thread_context.rb +1 -0
  107. data/lib/datadog/profiling/component.rb +13 -15
  108. data/lib/datadog/profiling/ext/dir_monkey_patches.rb +3 -3
  109. data/lib/datadog/ruby_version.rb +25 -0
  110. data/lib/datadog/symbol_database/component.rb +453 -128
  111. data/lib/datadog/symbol_database/configuration.rb +12 -4
  112. data/lib/datadog/symbol_database/extensions.rb +19 -0
  113. data/lib/datadog/symbol_database/extractor.rb +326 -150
  114. data/lib/datadog/symbol_database/file_hash.rb +3 -1
  115. data/lib/datadog/symbol_database/remote.rb +8 -3
  116. data/lib/datadog/symbol_database/scope_batcher.rb +7 -3
  117. data/lib/datadog/symbol_database/uploader.rb +9 -2
  118. data/lib/datadog/symbol_database.rb +22 -0
  119. data/lib/datadog/tracing/configuration/ext.rb +13 -0
  120. data/lib/datadog/tracing/configuration/settings.rb +17 -0
  121. data/lib/datadog/tracing/contrib/configuration/resolver.rb +7 -0
  122. data/lib/datadog/tracing/contrib/grpc/distributed/propagation.rb +2 -0
  123. data/lib/datadog/tracing/contrib/grpc.rb +1 -0
  124. data/lib/datadog/tracing/contrib/http/distributed/propagation.rb +2 -0
  125. data/lib/datadog/tracing/contrib/http.rb +1 -0
  126. data/lib/datadog/tracing/contrib/karafka/distributed/propagation.rb +2 -0
  127. data/lib/datadog/tracing/contrib/karafka.rb +1 -0
  128. data/lib/datadog/tracing/contrib/rack/middlewares.rb +3 -1
  129. data/lib/datadog/tracing/contrib/rack/route_inference.rb +3 -1
  130. data/lib/datadog/tracing/contrib/sidekiq/distributed/propagation.rb +2 -0
  131. data/lib/datadog/tracing/contrib/sidekiq.rb +1 -0
  132. data/lib/datadog/tracing/contrib/waterdrop/distributed/propagation.rb +2 -0
  133. data/lib/datadog/tracing/contrib/waterdrop.rb +1 -0
  134. data/lib/datadog/tracing/distributed/baggage.rb +2 -1
  135. data/lib/datadog/tracing/distributed/propagation.rb +33 -1
  136. data/lib/datadog/tracing/distributed/trace_context.rb +11 -2
  137. data/lib/datadog/tracing/ext.rb +9 -0
  138. data/lib/datadog/tracing/remote.rb +34 -3
  139. data/lib/datadog/tracing/trace_digest.rb +7 -0
  140. data/lib/datadog/tracing/trace_operation.rb +4 -1
  141. data/lib/datadog/tracing/tracer.rb +1 -0
  142. data/lib/datadog/version.rb +1 -1
  143. data/lib/datadog.rb +5 -1
  144. metadata +22 -6
@@ -21,42 +21,40 @@ void ruby_helpers_init(void) {
21
21
  to_s_id = rb_intern("to_s");
22
22
  }
23
23
 
24
- // Internal helper for raising pre-formatted syserr exceptions
25
- static NORETURN(void private_raise_syserr_formatted(int syserr_errno, const char *detailed_message, const char *static_message)) {
26
- VALUE exception = rb_syserr_new(syserr_errno, detailed_message);
27
- private_raise_exception(exception, static_message);
28
- }
29
-
30
24
  // Use `raise_syserr` the macro instead, as it provides additional argument checks.
31
25
  void private_raise_syserr(int syserr_errno, const char *fmt, ...) {
32
- FORMAT_VA_ERROR_MESSAGE(detailed_message, fmt);
33
- private_raise_syserr_formatted(syserr_errno, detailed_message, fmt);
26
+ va_list args;
27
+ va_start(args, fmt);
28
+ VALUE detailed_message = rb_vsprintf(fmt, args);
29
+ va_end(args);
30
+
31
+ VALUE exception = rb_syserr_new_str(syserr_errno, detailed_message);
32
+ private_raise_exception(exception, fmt);
34
33
  }
35
34
 
36
35
  typedef struct {
37
36
  VALUE exception_class;
38
37
  int syserr_errno;
39
- char exception_message[MAX_RAISE_MESSAGE_SIZE];
40
- char telemetry_message[MAX_RAISE_MESSAGE_SIZE];
38
+ const char *format_string;
39
+ va_list va_args;
41
40
  } raise_args;
42
41
 
42
+ // Called via rb_thread_call_with_gvl from private_grab_gvl_and_raise.
43
+ // Formats the message with rb_vsprintf (which requires the GVL) and raises.
43
44
  static void *trigger_raise(void *raise_arguments) {
44
45
  raise_args *args = (raise_args *) raise_arguments;
45
46
 
47
+ VALUE detailed_message = rb_vsprintf(args->format_string, args->va_args);
48
+
49
+ VALUE exception;
46
50
  if (args->syserr_errno) {
47
- private_raise_syserr_formatted(
48
- args->syserr_errno,
49
- args->exception_message,
50
- args->telemetry_message
51
- );
51
+ exception = rb_syserr_new_str(args->syserr_errno, detailed_message);
52
52
  } else {
53
- private_raise_error_formatted(
54
- args->exception_class,
55
- args->exception_message,
56
- args->telemetry_message
57
- );
53
+ exception = rb_exc_new_str(args->exception_class, detailed_message);
58
54
  }
59
55
 
56
+ private_raise_exception(exception, args->format_string);
57
+
60
58
  return NULL;
61
59
  }
62
60
 
@@ -71,11 +69,17 @@ void private_grab_gvl_and_raise(VALUE exception_class, int syserr_errno, const c
71
69
  args.syserr_errno = 0;
72
70
  }
73
71
 
74
- FORMAT_VA_ERROR_MESSAGE(formatted_exception_message, format_string);
75
- snprintf(args.exception_message, MAX_RAISE_MESSAGE_SIZE, "%s", formatted_exception_message);
76
- snprintf(args.telemetry_message, MAX_RAISE_MESSAGE_SIZE, "%s", format_string);
72
+ args.format_string = format_string;
73
+ va_start(args.va_args, format_string);
77
74
 
78
75
  if (is_current_thread_holding_the_gvl()) {
76
+ VALUE detailed_message = rb_vsprintf(format_string, args.va_args);
77
+ va_end(args.va_args);
78
+
79
+ VALUE wrapped_message = rb_sprintf(
80
+ "grab_gvl_and_raise called by thread holding the global VM lock: %"PRIsVALUE,
81
+ detailed_message
82
+ );
79
83
  char telemetry_message[MAX_RAISE_MESSAGE_SIZE];
80
84
  snprintf(
81
85
  telemetry_message,
@@ -83,20 +87,14 @@ void private_grab_gvl_and_raise(VALUE exception_class, int syserr_errno, const c
83
87
  "grab_gvl_and_raise called by thread holding the global VM lock: %s",
84
88
  format_string
85
89
  );
86
- char exception_message[MAX_RAISE_MESSAGE_SIZE];
87
- snprintf(
88
- exception_message,
89
- MAX_RAISE_MESSAGE_SIZE,
90
- "grab_gvl_and_raise called by thread holding the global VM lock: %s",
91
- args.exception_message
92
- );
93
- VALUE exception = rb_exc_new_cstr(rb_eRuntimeError, exception_message);
90
+ VALUE exception = rb_exc_new_str(rb_eRuntimeError, wrapped_message);
94
91
  private_raise_exception(exception, telemetry_message);
95
92
  }
96
93
 
97
94
  rb_thread_call_with_gvl(trigger_raise, &args);
98
95
 
99
- rb_bug("[ddtrace] Unexpected: Reached the end of grab_gvl_and_raise while raising '%s'\n", args.exception_message);
96
+ va_end(args.va_args);
97
+ rb_bug("[ddtrace] Unexpected: Reached the end of grab_gvl_and_raise while raising '%s'\n", format_string);
100
98
  }
101
99
 
102
100
  void private_raise_enforce_syserr(
@@ -107,10 +105,11 @@ void private_raise_enforce_syserr(
107
105
  int line,
108
106
  const char *function_name
109
107
  ) {
108
+ const char *format = "Failure returned by '%s' at %s:%d:in `%s'";
110
109
  if (have_gvl) {
111
- rb_exc_raise(rb_syserr_new_str(syserr_errno, rb_sprintf("Failure returned by '%s' at %s:%d:in `%s'", expression, file, line, function_name)));
110
+ private_raise_exception(rb_syserr_new_str(syserr_errno, rb_sprintf(format, expression, file, line, function_name)), format);
112
111
  } else {
113
- private_grab_gvl_and_raise(Qnil, syserr_errno, "Failure returned by '%s' at %s:%d:in `%s'", expression, file, line, function_name);
112
+ private_grab_gvl_and_raise(Qnil, syserr_errno, format, expression, file, line, function_name);
114
113
  }
115
114
  }
116
115
 
@@ -163,9 +162,16 @@ size_t rb_obj_memsize_of(VALUE obj);
163
162
  size_t ruby_obj_memsize_of(VALUE obj) {
164
163
  switch (rb_type(obj)) {
165
164
  case T_OBJECT:
165
+ // On Ruby 4.0, computing the size of a class/module/iclass seems to not be safe: `rb_obj_memsize_of` walks the
166
+ // per-namespace class extensions (`rb_class_classext_foreach` -> `classext_memsize` -> `rb_id_table_memsize`)
167
+ // and can crash the VM when called on objects tracked by heap profiling.
168
+ // See https://github.com/DataDog/dd-trace-rb/issues/5936. Class objects contribute negligibly to heap size,
169
+ // so we skip them (fall through to the `default` branch, returning 0) rather than risk a SIGSEGV.
170
+ #ifndef NO_SAFE_CLASS_MEMSIZE
166
171
  case T_MODULE:
167
172
  case T_CLASS:
168
173
  case T_ICLASS:
174
+ #endif
169
175
  case T_STRING:
170
176
  case T_ARRAY:
171
177
  case T_HASH:
@@ -9,6 +9,7 @@
9
9
  #include "time_helpers.h"
10
10
  #include "heap_recorder.h"
11
11
  #include "encoded_profile.h"
12
+ #include "collectors_thread_context.h"
12
13
 
13
14
  // Used to wrap a ddog_prof_Profile in a Ruby object and expose Ruby-level serialization APIs
14
15
  // This file implements the native bits of the Datadog::Profiling::StackRecorder class
@@ -177,6 +178,10 @@ typedef struct {
177
178
  heap_recorder *heap_recorder;
178
179
  bool heap_clean_after_gc_enabled;
179
180
 
181
+ // When set, _native_serialize will call thread_context_collector_on_serialize on this instance
182
+ // before serializing, so that threads suspended across the whole profile period still get sampled.
183
+ VALUE thread_context_collector_instance;
184
+
180
185
  pthread_mutex_t mutex_slot_one;
181
186
  profile_slot profile_slot_one;
182
187
  pthread_mutex_t mutex_slot_two;
@@ -320,6 +325,7 @@ static VALUE _native_new(VALUE klass) {
320
325
  // being leaked.
321
326
 
322
327
  state->heap_clean_after_gc_enabled = false;
328
+ state->thread_context_collector_instance = Qnil;
323
329
 
324
330
  ddog_prof_Slice_SampleType sample_types = {.ptr = all_sample_types, .len = ALL_VALUE_TYPES_COUNT};
325
331
 
@@ -391,6 +397,7 @@ static void initialize_profiles(stack_recorder_state *state, ddog_prof_Slice_Sam
391
397
  static void stack_recorder_typed_data_mark(void *state_ptr) {
392
398
  stack_recorder_state *state = (stack_recorder_state *) state_ptr;
393
399
 
400
+ rb_gc_mark(state->thread_context_collector_instance);
394
401
  heap_recorder_mark_pending_recordings(state->heap_recorder);
395
402
  }
396
403
 
@@ -515,12 +522,16 @@ static VALUE _native_serialize(DDTRACE_UNUSED VALUE _self, VALUE recorder_instan
515
522
  TypedData_Get_Struct(recorder_instance, stack_recorder_state, &stack_recorder_typed_data, state);
516
523
 
517
524
  ddog_Timespec finish_timestamp = system_epoch_now_timespec();
518
- // Need to do this while still holding on to the Global VM Lock; see comments on method for why
525
+ // Need to do this while still holding the Global VM Lock; see comments on method for why
519
526
  serializer_set_start_timestamp_for_next_profile(state, finish_timestamp);
520
527
 
528
+ if (state->thread_context_collector_instance != Qnil) {
529
+ thread_context_collector_on_serialize(state->thread_context_collector_instance);
530
+ }
531
+
521
532
  long heap_iteration_prep_start_time_ns = monotonic_wall_time_now_ns(DO_NOT_RAISE_ON_FAILURE);
522
533
  // Prepare the iteration on heap recorder we'll be doing outside the GVL. The preparation needs to
523
- // happen while holding on to the GVL.
534
+ // happen while holding the GVL.
524
535
  // NOTE: While rare, it's possible for the GVL to be released inside this function (see comments on `heap_recorder_update`)
525
536
  // and thus don't assume this is an "atomic" step -- other threads may get some running time in the meanwhile.
526
537
  heap_recorder_prepare_iteration(state->heap_recorder);
@@ -548,7 +559,7 @@ static VALUE _native_serialize(DDTRACE_UNUSED VALUE _self, VALUE recorder_instan
548
559
  rb_thread_call_without_gvl2(call_serialize_without_gvl, &args, NULL /* No interruption function needed in this case */, NULL /* Not needed */);
549
560
  }
550
561
 
551
- // Cleanup after heap recorder iteration. This needs to happen while holding on to the GVL.
562
+ // Cleanup after heap recorder iteration. This needs to happen while holding the GVL.
552
563
  heap_recorder_finish_iteration(state->heap_recorder);
553
564
 
554
565
  // NOTE: We are focusing on the serialization time outside of the GVL in this stat here. This doesn't
@@ -894,6 +905,9 @@ static ddog_Timespec system_epoch_now_timespec(void) {
894
905
  //
895
906
  // Assumption: This method gets called BEFORE restarting profiling -- e.g. there are no components attempting to
896
907
  // trigger samples at the same time.
908
+ //
909
+ // Note that tests call this method directly in the same process without forking,
910
+ // and in such a case non-current Threads keep running.
897
911
  static VALUE _native_reset_after_fork(DDTRACE_UNUSED VALUE self, VALUE recorder_instance) {
898
912
  stack_recorder_state *state;
899
913
  TypedData_Get_Struct(recorder_instance, stack_recorder_state, &stack_recorder_typed_data, state);
@@ -1147,3 +1161,10 @@ static VALUE _native_finalize_pending_heap_recordings(DDTRACE_UNUSED VALUE _self
1147
1161
 
1148
1162
  return Qtrue;
1149
1163
  }
1164
+
1165
+ void recorder_install_on_serialize(VALUE recorder_instance, VALUE thread_context_collector_instance) {
1166
+ stack_recorder_state *state;
1167
+ TypedData_Get_Struct(recorder_instance, stack_recorder_state, &stack_recorder_typed_data, state);
1168
+
1169
+ state->thread_context_collector_instance = enforce_thread_context_collector_instance(thread_context_collector_instance);
1170
+ }
@@ -29,4 +29,5 @@ void record_endpoint(VALUE recorder_instance, uint64_t local_root_span_id, ddog_
29
29
  __attribute__((warn_unused_result)) bool track_object(VALUE recorder_instance, VALUE new_object, unsigned int sample_weight, ddog_CharSlice alloc_class);
30
30
  void recorder_after_sample(VALUE recorder_instance);
31
31
  void recorder_after_gc_step(VALUE recorder_instance);
32
+ void recorder_install_on_serialize(VALUE recorder_instance, VALUE thread_context_collector_instance);
32
33
  VALUE enforce_recorder_instance(VALUE object);
@@ -4,7 +4,7 @@
4
4
  //
5
5
  // Specifically, when the profiler is sampling, we're never supposed to call into Ruby code (e.g. methods
6
6
  // implemented using Ruby code) or allocate Ruby objects.
7
- // That's because those events introduce thread switch points, and really we don't the VM switching between threads
7
+ // That's because those events introduce thread switch points, and really we don't want the VM switching between threads
8
8
  // in the middle of the profiler sampling. This includes raising exceptions.
9
9
  //
10
10
  // Raising exceptions as the very last operation, to stop the profiler is ok, but comes a caveat: raising exceptions
@@ -18,10 +18,12 @@
18
18
  // in most (all?) thread switch points, Ruby will check for interrupts and run the postponed jobs.
19
19
  //
20
20
  // Thus, if we set a flag while we're sampling (inside_unsafe_context), trigger the postponed job, and then only unset
21
- // the flag after sampling, he correct thing to happen is that the postponed job should never see the flag.
21
+ // the flag after sampling, the correct thing to happen is that the postponed job should never see the flag.
22
22
  //
23
23
  // If, however, we have a bug and there's a thread switch point, our postponed job will see the flag and immediately
24
24
  // stop the Ruby VM before further damage happens (and hopefully giving us a stack trace clearly pointing to the culprit).
25
+ //
26
+ // Note that this check currently does not detect Ruby object allocations, as those do not check for interrupts.
25
27
 
26
28
  void unsafe_api_calls_check_init(void);
27
29
 
@@ -29,16 +29,15 @@ void private_raise_exception(VALUE exception, const char *static_message) {
29
29
  rb_exc_raise(exception);
30
30
  }
31
31
 
32
- // Helper for raising pre-formatted exceptions
33
- void private_raise_error_formatted(VALUE exception_class, const char *detailed_message, const char *static_message) {
34
- VALUE exception = rb_exc_new_cstr(exception_class, detailed_message);
35
- private_raise_exception(exception, static_message);
36
- }
37
-
38
32
  // Use `raise_error` the macro instead, as it provides additional argument checks.
39
33
  void private_raise_error(VALUE exception_class, const char *fmt, ...) {
40
- FORMAT_VA_ERROR_MESSAGE(detailed_message, fmt);
41
- private_raise_error_formatted(exception_class, detailed_message, fmt);
34
+ va_list args;
35
+ va_start(args, fmt);
36
+ VALUE detailed_message = rb_vsprintf(fmt, args);
37
+ va_end(args);
38
+
39
+ VALUE exception = rb_exc_new_str(exception_class, detailed_message);
40
+ private_raise_exception(exception, fmt);
42
41
  }
43
42
 
44
43
  VALUE datadog_gem_version(void) {
@@ -47,11 +47,6 @@ NORETURN(
47
47
  __attribute__ ((format (printf, 2, 3)));
48
48
  );
49
49
 
50
- // Internal helper for raising pre-formatted exceptions
51
- NORETURN(
52
- void private_raise_error_formatted(VALUE exception_class, const char *detailed_message, const char *static_message)
53
- );
54
-
55
50
  // Raises an exception with separate telemetry-safe and detailed messages.
56
51
  // NOTE: Raising an exception always invokes Ruby code so it requires the GVL and is not compatible with "debug_enter_unsafe_context".
57
52
  // @see debug_enter_unsafe_context
@@ -61,13 +56,6 @@ NORETURN(
61
56
 
62
57
  #define MAX_RAISE_MESSAGE_SIZE 256
63
58
 
64
- #define FORMAT_VA_ERROR_MESSAGE(buf, fmt) \
65
- char buf[MAX_RAISE_MESSAGE_SIZE]; \
66
- va_list buf##_args; \
67
- va_start(buf##_args, fmt); \
68
- vsnprintf(buf, MAX_RAISE_MESSAGE_SIZE, fmt, buf##_args); \
69
- va_end(buf##_args);
70
-
71
59
  // Helper to retrieve Datadog::VERSION::STRING
72
60
  VALUE datadog_gem_version(void);
73
61
 
@@ -21,6 +21,12 @@ void rb_objspace_each_objects(
21
21
  // from standard library exception classes like NameError.
22
22
  static ID id_mesg;
23
23
 
24
+ // ID for the fiber-local key that backs the method-probe re-entrancy guard.
25
+ // Storage is the same hashtable that backs Thread#[] / Thread#[]=, but accessed
26
+ // directly via rb_thread_local_aref / rb_thread_local_aset so that user-installed
27
+ // method probes on Thread#[] / Thread#[]= cannot intercept guard reads/writes.
28
+ static ID id_datadog_di_in_probe;
29
+
24
30
  // Returns whether the argument is an IMEMO of type ISEQ.
25
31
  static bool ddtrace_imemo_iseq_p(VALUE v) {
26
32
  return rb_objspace_internal_object_p(v) && RB_TYPE_P(v, T_IMEMO) && ddtrace_imemo_type(v) == IMEMO_TYPE_ISEQ;
@@ -75,6 +81,71 @@ static VALUE exception_message(DDTRACE_UNUSED VALUE _self, VALUE exception) {
75
81
  return rb_ivar_get(exception, id_mesg);
76
82
  }
77
83
 
84
+ /*
85
+ * call-seq:
86
+ * DI.in_probe? -> true | false
87
+ *
88
+ * Returns whether the current fiber is currently inside DI probe processing.
89
+ * Reads the same fiber-local storage as Thread.current[:datadog_di_in_probe]
90
+ * but bypasses Thread#[] method dispatch — a user method probe on Thread#[]
91
+ * cannot observe or intercept this call.
92
+ *
93
+ * @api private
94
+ */
95
+ static VALUE in_probe_p(DDTRACE_UNUSED VALUE _self) {
96
+ VALUE v = rb_thread_local_aref(rb_thread_current(), id_datadog_di_in_probe);
97
+ return RTEST(v) ? Qtrue : Qfalse;
98
+ }
99
+
100
+ /*
101
+ * call-seq:
102
+ * DI.enter_probe -> nil
103
+ *
104
+ * Marks the current fiber as inside DI probe processing. Writes to the same
105
+ * fiber-local storage as Thread.current[:datadog_di_in_probe] = true, but
106
+ * bypasses Thread#[]= method dispatch — a user method probe on Thread#[]=
107
+ * cannot observe or intercept this call.
108
+ *
109
+ * @api private
110
+ */
111
+ static VALUE enter_probe(DDTRACE_UNUSED VALUE _self) {
112
+ rb_thread_local_aset(rb_thread_current(), id_datadog_di_in_probe, Qtrue);
113
+ return Qnil;
114
+ }
115
+
116
+ /*
117
+ * call-seq:
118
+ * DI.leave_probe -> nil
119
+ *
120
+ * Marks the current fiber as no longer inside DI probe processing. Writes to
121
+ * the same fiber-local storage as Thread.current[:datadog_di_in_probe] = nil,
122
+ * but bypasses Thread#[]= method dispatch — a user method probe on Thread#[]=
123
+ * cannot observe or intercept this call.
124
+ *
125
+ * @api private
126
+ */
127
+ static VALUE leave_probe(DDTRACE_UNUSED VALUE _self) {
128
+ rb_thread_local_aset(rb_thread_current(), id_datadog_di_in_probe, Qnil);
129
+ return Qnil;
130
+ }
131
+
132
+ /*
133
+ * call-seq:
134
+ * DI.hash?(obj) -> true | false
135
+ *
136
+ * Returns whether the given object is a Hash via a direct type check
137
+ * (RB_TYPE_P), bypassing Kernel#is_a? method dispatch. Used in the method
138
+ * probe wrapper (the Ruby < 3 argument-serialization split) to test whether
139
+ * the trailing argument is a hash without giving a user-installed method
140
+ * probe on Kernel#is_a? a chance to recurse. Matches Hash and its
141
+ * subclasses, like is_a?(Hash), since their instances are still T_HASH.
142
+ *
143
+ * @api private
144
+ */
145
+ static VALUE is_hash(DDTRACE_UNUSED VALUE _self, VALUE obj) {
146
+ return RB_TYPE_P(obj, T_HASH) ? Qtrue : Qfalse;
147
+ }
148
+
78
149
  // rb_iseq_type was added in Ruby 3.1 (commit 89a02d89 by Koichi Sasada,
79
150
  // 2021-12-19). It returns the iseq type as a Symbol. On Ruby < 3.1 this
80
151
  // function does not exist, so have_func('rb_iseq_type') in extconf.rb
@@ -117,10 +188,15 @@ static VALUE iseq_type(DDTRACE_UNUSED VALUE _self, VALUE iseq_val) {
117
188
 
118
189
  void di_init(VALUE datadog_module) {
119
190
  id_mesg = rb_intern("mesg");
191
+ id_datadog_di_in_probe = rb_intern("datadog_di_in_probe");
120
192
 
121
193
  VALUE di_module = rb_define_module_under(datadog_module, "DI");
122
194
  rb_define_singleton_method(di_module, "all_iseqs", all_iseqs, 0);
123
195
  rb_define_singleton_method(di_module, "exception_message", exception_message, 1);
196
+ rb_define_singleton_method(di_module, "in_probe?", in_probe_p, 0);
197
+ rb_define_singleton_method(di_module, "enter_probe", enter_probe, 0);
198
+ rb_define_singleton_method(di_module, "leave_probe", leave_probe, 0);
199
+ rb_define_singleton_method(di_module, "hash?", is_hash, 1);
124
200
  #ifdef HAVE_RB_ISEQ_TYPE
125
201
  rb_define_singleton_method(di_module, "iseq_type", iseq_type, 1);
126
202
  #endif
@@ -41,6 +41,12 @@ Datadog::LibdatadogExtconfHelpers.dump_mkmf_log_on_failure!
41
41
  # But we can enable it in CI, so that we quickly spot any new warnings that just got introduced.
42
42
  append_cflags '-Werror' if ENV['DATADOG_GEM_CI'] == 'true'
43
43
 
44
+ # TEMPORARY STOPGAP: libdatadog v36's vendored `common.h` ships duplicate typedefs
45
+ # (a header-dedup regression), which `-Werror` turns into fatal
46
+ # `-Wtypedef-redefinition` errors under C11/gnu11. Keep it a warning until a fixed
47
+ # header lands upstream in libdatadog/libdatadog-rb. Remove this once that ships.
48
+ append_cflags '-Wno-error=typedef-redefinition' if ENV['DATADOG_GEM_CI'] == 'true'
49
+
44
50
  # Older gcc releases may not default to C99 and we need to ask for this. This is also used:
45
51
  # * by upstream Ruby -- search for gnu99 in the codebase
46
52
  # * by msgpack, another datadog gem dependency
@@ -10,7 +10,7 @@ module Datadog
10
10
  module LibdatadogExtconfHelpers
11
11
  # Used to make sure the correct gem version gets loaded, as extconf.rb does not get run with "bundle exec" and thus
12
12
  # may see multiple libdatadog versions. See https://github.com/DataDog/dd-trace-rb/pull/2531 for the horror story.
13
- LIBDATADOG_VERSION = '~> 33.0.0.1.0'
13
+ LIBDATADOG_VERSION = '~> 36.0.0.1.0'
14
14
 
15
15
  # Used as an workaround for a limitation with how dynamic linking works in environments where the datadog gem and
16
16
  # libdatadog are moved after the extension gets compiled.
@@ -17,11 +17,13 @@ module Datadog
17
17
 
18
18
  @endpoint_uri = if endpoint
19
19
  URI(endpoint) #: URI::HTTP
20
+ elsif Datadog.configuration.site
21
+ host = Datadog.configuration.site.dup
22
+ host.prepend("app.") if host.count(".") == 1
23
+
24
+ URI::HTTPS.build(host: host, path: DEFAULT_PATH)
20
25
  else
21
- URI::HTTPS.build(
22
- host: Datadog.configuration.site || DEFAULT_SITE,
23
- path: DEFAULT_PATH
24
- )
26
+ URI::HTTPS.build(host: DEFAULT_SITE, path: DEFAULT_PATH)
25
27
  end
26
28
 
27
29
  @headers = {
@@ -31,16 +31,19 @@ module Datadog
31
31
  # uses `sinatra.route` with a string like "GET /users/:id"
32
32
  # Grape
33
33
  # uses `grape.routing_args` with a hash with a `:route_info` key
34
- # that contains a `Grape::Router::Route` object that contains
35
- # `Grape::Router::Pattern` object with an `origin` method
34
+ # that contains a {Grape::Router::Route} object that contains
35
+ # {Grape::Router::Pattern} object with an `origin` method
36
+ # Rails with `action_pack` tracing contrib (fast path)
37
+ # `datadog.action_dispatch.route` stores the {Journey::Route}
38
+ # object set by the tracer at routing time
36
39
  # Rails < 7.1 (slow path)
37
- # uses `action_dispatch.routes` to store `ActionDispatch::Routing::RouteSet`
40
+ # uses `action_dispatch.routes` to store {ActionDispatch::Routing::RouteSet}
38
41
  # which can recognize requests
39
42
  # Rails > 7.1 (fast path)
40
43
  # uses `action_dispatch.route_uri_pattern` with a string like
41
44
  # "/users/:id(.:format)"
42
45
  # Rails > 8.1.1 (fast path)
43
- # uses `action_dispatch.route` to store the ActionDispatch::Journey::Route
46
+ # uses `action_dispatch.route` to store the {ActionDispatch::Journey::Route}
44
47
  # that matched when the request was routed
45
48
  #
46
49
  # WARNING: This method works only *after* the request has been routed.
@@ -50,6 +53,12 @@ module Datadog
50
53
  # In Rails < 7.1 it also will not be set even if a route was found,
51
54
  # but in this case `action_dispatch.request.path_parameters` won't be empty.
52
55
  def self.route_pattern(request)
56
+ # NOTE: Requests from contribs like AWS Lambda don't provide a usable
57
+ # `::Rack::Request#env`, so infer the route from the path instead
58
+ unless request.respond_to?(:env)
59
+ return Tracing::Contrib::Rack::RouteInference.infer(request.path.to_s)
60
+ end
61
+
53
62
  if request.env.key?(GRAPE_ROUTE_KEY)
54
63
  pattern = request.env[GRAPE_ROUTE_KEY][:route_info]&.pattern&.origin
55
64
  "#{request.script_name}#{pattern}"
@@ -22,7 +22,7 @@ module Datadog
22
22
  return
23
23
  end
24
24
 
25
- if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('3.3') && ffi_version < Gem::Version.new('1.16.0')
25
+ if RubyVersion.is?('>= 3.3') && ffi_version < Gem::Version.new('1.16.0')
26
26
  Datadog.logger.warn(
27
27
  'AppSec is not supported in Ruby versions above 3.3.0 when using `ffi` versions older than 1.16.0, ' \
28
28
  'and will be forcibly disabled due to a memory leak in `ffi`. ' \
@@ -134,6 +134,13 @@ module Datadog
134
134
  end
135
135
  end
136
136
 
137
+ # NOTE: A value of 0 (or less) disables request body collection
138
+ option :body_parsing_size_limit do |o|
139
+ o.type :int
140
+ o.env 'DD_APPSEC_BODY_PARSING_SIZE_LIMIT' # bytes
141
+ o.default 10_485_760
142
+ end
143
+
137
144
  option :waf_debug do |o|
138
145
  o.env 'DD_APPSEC_WAF_DEBUG'
139
146
  o.default false
@@ -407,6 +414,12 @@ module Datadog
407
414
  o.env 'DD_API_SECURITY_MAX_DOWNSTREAM_REQUEST_BODY_ANALYSIS'
408
415
  o.default 1
409
416
  end
417
+
418
+ option :max_downstream_body_bytes do |o|
419
+ o.type :int
420
+ o.env 'DD_API_SECURITY_MAX_DOWNSTREAM_BODY_BYTES'
421
+ o.default 10_485_760
422
+ end
410
423
  end
411
424
  end
412
425
 
@@ -20,7 +20,7 @@ module Datadog
20
20
  ActiveContextError = Class.new(StandardError) # steep:ignore IncompatibleAssignment
21
21
 
22
22
  # TODO: add delegators for active trace span
23
- attr_reader :trace, :span
23
+ attr_reader :trace, :span, :metrics
24
24
 
25
25
  # Shared mutable storage for counters, flags, and data accumulated during
26
26
  # the request's lifecycle.
@@ -103,7 +103,8 @@ module Datadog
103
103
  end
104
104
 
105
105
  def extract_schema!
106
- waf_result = @waf_runner.run({'waf.context.processor' => {'extract-schema' => true}}, {})
106
+ persistent_data = {'waf.context.processor' => {'extract-schema' => true}}
107
+ waf_result = run_waf(persistent_data, {}, Datadog.configuration.appsec.waf_timeout)
107
108
  security_event = AppSec::SecurityEvent.new(waf_result, trace: trace, span: span)
108
109
 
109
110
  @state[:schema_extracted] = security_event.schema?
@@ -116,6 +117,7 @@ module Datadog
116
117
 
117
118
  Metrics::Exporter.export_waf_metrics(@metrics.waf, @span)
118
119
  Metrics::Exporter.export_rasp_metrics(@metrics.rasp, @span)
120
+ Metrics::Exporter.export_downstream_response_metrics(@metrics.downstream_responses, @span)
119
121
  end
120
122
 
121
123
  def export_request_telemetry
@@ -15,6 +15,10 @@ module Datadog
15
15
  # Extracts WAF input addresses from normalized AWS Lambda API Gateway event payloads.
16
16
  # @api private
17
17
  module WAFAddresses
18
+ BASE64_CHARS_PER_GROUP = 4
19
+ BASE64_BYTES_PER_GROUP = 3
20
+ BASE64_PADDING_BYTE = "=".ord
21
+
18
22
  module_function
19
23
 
20
24
  def from_request(payload)
@@ -27,10 +31,11 @@ module Datadog
27
31
  'server.request.uri.raw' => build_fullpath(payload),
28
32
  'server.request.headers' => headers,
29
33
  'server.request.headers.no_cookies' => headers.dup.tap { |h| h.delete('cookie') },
30
- 'http.client_ip' => extract_client_ip(payload['source_ip'], headers),
31
34
  'server.request.method' => payload['method'],
32
35
  'server.request.body' => parse_body(payload, headers),
33
- 'server.request.path_params' => payload['path_params']
36
+ 'server.request.body.byte_length' => body_byte_length(payload),
37
+ 'server.request.path_params' => payload['path_params'],
38
+ 'http.client_ip' => extract_client_ip(payload['source_ip'], headers)
34
39
  }
35
40
 
36
41
  data.compact!
@@ -44,7 +49,9 @@ module Datadog
44
49
  data = {
45
50
  'server.response.status' => payload['status_code']&.to_s,
46
51
  'server.response.headers' => headers,
47
- 'server.response.headers.no_cookies' => headers.dup.tap { |h| h.delete('set-cookie') }
52
+ 'server.response.headers.no_cookies' => headers.dup.tap { |h| h.delete('set-cookie') },
53
+ 'server.response.body' => parse_body(payload, headers),
54
+ 'server.response.body.byte_length' => body_byte_length(payload)
48
55
  }
49
56
 
50
57
  data.compact!
@@ -94,7 +101,9 @@ module Datadog
94
101
  body = payload['body']
95
102
  return unless body
96
103
 
97
- body = Core::Utils::Base64Codec.strict_decode64(body) if payload['base64_encoded']
104
+ if (byte_length = body_byte_length(payload))
105
+ return if byte_length > Datadog.configuration.appsec.body_parsing_size_limit
106
+ end
98
107
 
99
108
  content_type = headers['content-type']
100
109
  return unless content_type
@@ -102,7 +111,31 @@ module Datadog
102
111
  media_type = AppSec::Utils::HTTP::MediaType.parse(content_type)
103
112
  return unless media_type
104
113
 
114
+ body = Core::Utils::Base64Codec.strict_decode64(body) if payload['base64_encoded']
105
115
  AppSec::Utils::HTTP::Body.parse(body, media_type: media_type)
116
+ rescue ArgumentError => e
117
+ AppSec.telemetry.report(e, description: 'AppSec: Failed to decode base64 body')
118
+
119
+ nil
120
+ end
121
+
122
+ def body_byte_length(payload)
123
+ body = payload['body']
124
+
125
+ return unless body
126
+ return body.bytesize unless payload['base64_encoded']
127
+
128
+ # NOTE: Base64 packs every 3 bytes into 4 characters and pads the last
129
+ # group with up to two "=" bytes. The decoded length is therefore
130
+ # derivable from the encoded length, letting us measure the raw
131
+ # body size without allocating the decoded string.
132
+ padding = 0
133
+ if body.getbyte(-1) == BASE64_PADDING_BYTE
134
+ padding = 1
135
+ padding = 2 if body.getbyte(-2) == BASE64_PADDING_BYTE
136
+ end
137
+
138
+ body.bytesize / BASE64_CHARS_PER_GROUP * BASE64_BYTES_PER_GROUP - padding
106
139
  end
107
140
  end
108
141
  end