gapic-common 1.0.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 780d9d8bf815864f7a6074a368a30594dd92143b0e5842bc511a9f9d7aea1fd5
4
- data.tar.gz: 80a0287351754d6e3a80440e16fb4ddeb4cc79a72c761f6673309c43abfac5c1
3
+ metadata.gz: b913235ab6a4508add68839ed5249a5593fe35543c12d7c5a0fd10da958d52d4
4
+ data.tar.gz: 25da91337dde92ebab37ce20f20d6795c3eb15f70480e488fb5a76e0c3e771ab
5
5
  SHA512:
6
- metadata.gz: 61a3cd4ae5539ec36ed6972d02261beb91711db6e6ed7069eec654e6fdd009b2c6ff673596c2fc17688ddba45e2b90438d033bff526f93a836ec4771a57c6e83
7
- data.tar.gz: 24aad16e19d8a7d0411481169b0b0235d9de530bc41e232904e9901fe30e3a2bf3df4a6801938e6cd30af1aab8a9634ededd4bc8a36ff8b0f73342195834c137
6
+ metadata.gz: '093cefa2ecd695bc76f1a9bc0b90934f946e8953576b110abb834e60efa6b849e684e39d86d0c02ca560fb52b221261e348c5bf4ff7caf1c2b45256c7ea3ff21'
7
+ data.tar.gz: 12e1f11af015c7ee7df9dc3049123b998e3a3aa0d6fb7cf39cb5804620a9bd1883870b05526d8d1418d7162c2f883b1fdafa2f1731ef8ea216a53d8e884f3979
data/CHANGELOG.md CHANGED
@@ -1,5 +1,75 @@
1
1
  # Release History
2
2
 
3
+ ### 1.6.1 (2026-10-29)
4
+
5
+ #### Documentation
6
+
7
+ * link to the published Ruby version support policy ([#91](https://github.com/googleapis/ruby-core-libraries/issues/91))
8
+
9
+ ### 1.6.0 (2026-10-22)
10
+
11
+ #### Features
12
+
13
+ * require grpc >= 1.84.1 ([#90](https://github.com/googleapis/ruby-core-libraries/issues/90))
14
+ #### Bug Fixes
15
+
16
+ * ignore inherited Service constants in normalize_service ([#71](https://github.com/googleapis/ruby-core-libraries/issues/71)) ([47c7e98](https://github.com/googleapis/ruby-core-libraries/commit/47c7e9854904caa59955aab31a6fdacd0af200b8)), refs [#70](https://github.com/googleapis/ruby-core-libraries/issues/70)
17
+
18
+ ### 1.5.1 (2026-09-30)
19
+
20
+ #### Bug Fixes
21
+
22
+ * tighten path template matching in the REST transcoder ([#83](https://github.com/googleapis/ruby-core-libraries/issues/83))
23
+
24
+ ### 1.5.0 (2026-09-29)
25
+
26
+ #### Features
27
+
28
+ * Resumable Media Upload functionality implementation ([#72](https://github.com/googleapis/ruby-core-libraries/issues/72))
29
+ #### Documentation
30
+
31
+ * remove stale preview notice and disclaimer from READMEs ([#77](https://github.com/googleapis/ruby-core-libraries/issues/77))
32
+
33
+ ### 1.4.1 (2026-09-28)
34
+
35
+ #### Bug Fixes
36
+
37
+ * validate path parameters and prevent traversal/injection in REST transcoder ([#67](https://github.com/googleapis/ruby-core-libraries/issues/67))
38
+
39
+ ### 1.4.0 (2026-09-23)
40
+
41
+ #### Features
42
+
43
+ * add custom predicate matching to RetryPolicy ([#59](https://github.com/googleapis/ruby-core-libraries/issues/59))
44
+ #### Bug Fixes
45
+
46
+ * require grpc >= 1.83 for post-quantum key exchange ([#73](https://github.com/googleapis/ruby-core-libraries/issues/73))
47
+ * only use emit_default for proto messages ([#75](https://github.com/googleapis/ruby-core-libraries/issues/75))
48
+
49
+ ### 1.3.0 (2026-03-05)
50
+
51
+ #### Features
52
+
53
+ * add jitter to retries ([#54](https://github.com/googleapis/ruby-core-libraries/issues/54))
54
+
55
+ ### 1.2.0 (2025-09-04)
56
+
57
+ #### Features
58
+
59
+ * update google-protobuf dependency ([#41](https://github.com/googleapis/ruby-core-libraries/issues/41))
60
+
61
+ ### 1.1.0 (2025-08-11)
62
+
63
+ #### Features
64
+
65
+ * add http binding configuration ([#38](https://github.com/googleapis/ruby-core-libraries/issues/38))
66
+
67
+ ### 1.0.1 (2025-07-17)
68
+
69
+ #### Bug Fixes
70
+
71
+ * Removed log preprocessing of large payload data when logging is disabled ([#35](https://github.com/googleapis/ruby-core-libraries/issues/35))
72
+
3
73
  ### 1.0.0 (2025-04-30)
4
74
 
5
75
  #### Features
data/README.md CHANGED
@@ -15,14 +15,41 @@ convenient and idiomatic API surface to callers.
15
15
 
16
16
  ## Supported Ruby Versions
17
17
 
18
- This library is supported on Ruby 3.0+.
18
+ This library is supported on Ruby 3.2+.
19
19
 
20
- Google provides official support for Ruby versions that are actively supported
21
- by Ruby Core—that is, Ruby versions that are either in normal maintenance or in
22
- security maintenance, and not end of life. Older versions of Ruby _may_ still
23
- work, but are unsupported and not recommended. See
24
- https://www.ruby-lang.org/en/downloads/branches/ for details about the Ruby
25
- support schedule.
20
+ Google provides official support for Ruby versions as described in the
21
+ [Supported Ruby versions](https://docs.cloud.google.com/ruby/getting-started/supported-ruby-versions)
22
+ policy. Older versions of Ruby _may_ still work, but are unsupported and not
23
+ recommended.
24
+
25
+ ## Post-Quantum Key Exchange
26
+
27
+ Clients built on this library negotiate the hybrid post-quantum key exchange
28
+ group `X25519MLKEM768` — classical X25519 paired with ML-KEM-768 ([NIST FIPS
29
+ 203][]) — over TLS 1.3. No application code changes are required, because the
30
+ handshake belongs to the transport layer. The two transports source that
31
+ support differently:
32
+
33
+ | Transport | Cryptographic provider | Requirement | Enforced by this gem? |
34
+ | --- | --- | --- | --- |
35
+ | gRPC | BoringSSL, vendored inside the `grpc` gem | `grpc >= 1.83` | Yes |
36
+ | REST | Host system OpenSSL, via `Net::HTTP` and Faraday | OpenSSL `>= 3.5` | No |
37
+
38
+ gRPC clients get post-quantum key exchange automatically: `gapic-common`
39
+ depends on `grpc >= 1.83`, the first release to offer `X25519MLKEM768` in the
40
+ TLS ClientHello by default.
41
+
42
+ The REST requirement cannot be expressed as a gem dependency. Ruby's `openssl`
43
+ is a default gem bound to whatever `libssl` the host provides, and ML-KEM first
44
+ ships in OpenSSL 3.5. On an older host, REST connections negotiate classical
45
+ X25519 instead — a safe fallback rather than an error, but not post-quantum. To
46
+ check the OpenSSL your Ruby is linked against:
47
+
48
+ ```sh
49
+ ruby -ropenssl -e 'puts OpenSSL::OPENSSL_LIBRARY_VERSION'
50
+ ```
51
+
52
+ [NIST FIPS 203]: https://csrc.nist.gov/pubs/fips/203/final
26
53
 
27
54
  ## Contributing
28
55
 
@@ -32,9 +59,6 @@ See the {file:CONTRIBUTING.md CONTRIBUTING} documentation for more information o
32
59
 
33
60
  ## Versioning
34
61
 
35
- This library is currently a **preview** with no guarantees of stability or support. Please get
36
- involved and let us know if you find it useful and we'll work towards a stable version.
37
-
38
- ## Disclaimer
62
+ This library follows [Semantic Versioning](http://semver.org/).
39
63
 
40
- This is not an official Google product.
64
+ This library is considered to be stable and will not have backwards-incompatible changes introduced in subsequent minor releases.
@@ -30,8 +30,9 @@ module Gapic
30
30
  # @param initial_delay [Numeric] Initial delay in seconds.
31
31
  # @param multiplier [Numeric] The delay scaling factor for each subsequent retry attempt.
32
32
  # @param max_delay [Numeric] Maximum delay in seconds.
33
+ # @param jitter [Numeric] Random jitter added to the delay in seconds.
33
34
  #
34
- def initialize retry_codes: nil, initial_delay: nil, multiplier: nil, max_delay: nil
35
+ def initialize retry_codes: nil, initial_delay: nil, multiplier: nil, max_delay: nil, jitter: nil
35
36
  super
36
37
  end
37
38
  end
@@ -19,6 +19,12 @@ module Gapic
19
19
  ##
20
20
  # Gapic Common retry policy base class.
21
21
  #
22
+ # A policy distinguishes "set to this value" from "never set". Every setting is stored as `nil`
23
+ # until someone supplies it, and the reader for each substitutes the corresponding `DEFAULT_`
24
+ # constant on the way out, so a reader can never say which of the two happened. That distinction is
25
+ # what lets {#apply_defaults} fill in gaps without overwriting a caller's choices, and {#overrides}
26
+ # report what a caller actually asked for.
27
+ #
22
28
  class RetryPolicy
23
29
  # @return [Numeric] Default initial delay in seconds.
24
30
  DEFAULT_INITIAL_DELAY = 1
@@ -31,6 +37,11 @@ module Gapic
31
37
  # @return [Numeric] Default timeout threshold value in seconds.
32
38
  DEFAULT_TIMEOUT = 3600 # One hour
33
39
 
40
+ # @private
41
+ # @return [Numeric] Default random jitter added to delay in seconds.
42
+ DEFAULT_JITTER = 1.0
43
+ private_constant :DEFAULT_JITTER
44
+
34
45
  ##
35
46
  # Create new Gapic::Common::RetryPolicy instance.
36
47
  #
@@ -39,14 +50,27 @@ module Gapic
39
50
  # @param multiplier [Numeric] The delay scaling factor for each subsequent retry attempt.
40
51
  # @param retry_codes [Array<String|Integer>] List of retry codes.
41
52
  # @param timeout [Numeric] Timeout threshold value in seconds.
53
+ # @param jitter [Numeric] Random jitter added to the delay in seconds.
54
+ # @param retry_predicate [Proc, nil] The predicate to evaluate whether to retry on a given error. Optional.
55
+ # If the predicate is specified, it is run first. If it returns nil, the decision on
56
+ # whether to retry is made on the basis of retry_codes. Otherwise, the truthiness of
57
+ # the return value determines whether to retry.
42
58
  #
43
- def initialize initial_delay: nil, max_delay: nil, multiplier: nil, retry_codes: nil, timeout: nil
59
+ def initialize initial_delay: nil, max_delay: nil, multiplier: nil, retry_codes: nil, timeout: nil,
60
+ jitter: nil, retry_predicate: nil
61
+ raise ArgumentError, "jitter cannot be negative" if jitter&.negative?
62
+ if retry_predicate && !retry_predicate.respond_to?(:call)
63
+ raise ArgumentError, "retry_predicate must respond to :call"
64
+ end
65
+
44
66
  # Instance values are set as `nil` to determine whether values are overriden from default.
45
67
  @initial_delay = initial_delay
46
68
  @max_delay = max_delay
47
69
  @multiplier = multiplier
48
70
  @retry_codes = convert_codes retry_codes
49
71
  @timeout = timeout
72
+ @jitter = jitter
73
+ @retry_predicate = retry_predicate
50
74
  start!
51
75
  end
52
76
 
@@ -75,6 +99,52 @@ module Gapic
75
99
  @timeout || DEFAULT_TIMEOUT
76
100
  end
77
101
 
102
+ # @return [Numeric] Random jitter added to the delay in seconds.
103
+ def jitter
104
+ @jitter || DEFAULT_JITTER
105
+ end
106
+
107
+ ##
108
+ # The predicate to evaluate whether to retry on a given error. Optional.
109
+ #
110
+ # When a predicate is specified:
111
+ # 1. The predicate is executed first on the error.
112
+ # 2. If it returns nil, the decision on whether to retry is made on the basis of retry_codes.
113
+ # 3. Otherwise, the truthiness of the return value determines whether to retry.
114
+ #
115
+ # @return [Proc, nil]
116
+ def retry_predicate
117
+ @retry_predicate
118
+ end
119
+
120
+ ##
121
+ # @private
122
+ # The settings this policy actually carries, as keyword arguments for {RetryPolicy.initialize}.
123
+ #
124
+ # A key is present only if that setting was explicitly supplied; a key that was never set is
125
+ # absent rather than `nil`. This is what the readers cannot tell you — {#max_delay} returns
126
+ # {DEFAULT_MAX_DELAY} whether the caller chose that number or said nothing — so it is the only
127
+ # safe way to carry one policy's settings onto another without dragging defaults along, and
128
+ # without mistaking a deliberate choice that happens to equal a default for silence.
129
+ #
130
+ # An empty `retry_codes` list counts as unset. It retries nothing, which is exactly what an
131
+ # unset list does, so there is nothing for it to carry.
132
+ #
133
+ # @return [Hash{Symbol=>Object}] Explicitly set settings only
134
+ def overrides
135
+ # Assigns nil, and so omits the key, when the list is absent or empty.
136
+ retry_codes = @retry_codes unless @retry_codes.nil? || @retry_codes.empty?
137
+ {
138
+ initial_delay: @initial_delay,
139
+ max_delay: @max_delay,
140
+ multiplier: @multiplier,
141
+ retry_codes: retry_codes,
142
+ timeout: @timeout,
143
+ jitter: @jitter,
144
+ retry_predicate: @retry_predicate
145
+ }.compact
146
+ end
147
+
78
148
  ##
79
149
  # Returns a duplicate in a non-executing state, i.e. with the deadline
80
150
  # and current delay reset.
@@ -86,7 +156,9 @@ module Gapic
86
156
  max_delay: @max_delay,
87
157
  multiplier: @multiplier,
88
158
  retry_codes: @retry_codes,
89
- timeout: @timeout
159
+ timeout: @timeout,
160
+ jitter: @jitter,
161
+ retry_predicate: @retry_predicate
90
162
  end
91
163
 
92
164
  ##
@@ -161,6 +233,13 @@ module Gapic
161
233
  # @return [Boolean] Whether this error should be retried.
162
234
  #
163
235
  def retry_error? error
236
+ # Run predicate first. If it returns nil, decision is made on the basis of retry_codes.
237
+ # Otherwise return truthiness.
238
+ if @retry_predicate.respond_to? :call
239
+ result = @retry_predicate.call error
240
+ return !!result unless result.nil?
241
+ end
242
+
164
243
  (defined?(::GRPC) && error.is_a?(::GRPC::BadStatus) && retry_codes.include?(error.code)) ||
165
244
  (error.respond_to?(:response_status) &&
166
245
  retry_codes.include?(ErrorCodes.grpc_error_for(error.response_status)))
@@ -182,10 +261,12 @@ module Gapic
182
261
  #
183
262
  def apply_defaults retry_policy
184
263
  return unless retry_policy.is_a? Hash
185
- @retry_codes ||= convert_codes retry_policy[:retry_codes]
186
- @initial_delay ||= retry_policy[:initial_delay]
187
- @multiplier ||= retry_policy[:multiplier]
188
- @max_delay ||= retry_policy[:max_delay]
264
+ @retry_codes ||= convert_codes retry_policy[:retry_codes]
265
+ @initial_delay ||= retry_policy[:initial_delay]
266
+ @multiplier ||= retry_policy[:multiplier]
267
+ @max_delay ||= retry_policy[:max_delay]
268
+ @jitter ||= retry_policy[:jitter]
269
+ @retry_predicate ||= retry_policy[:retry_predicate]
189
270
 
190
271
  self
191
272
  end
@@ -197,30 +278,35 @@ module Gapic
197
278
  other.max_delay == max_delay &&
198
279
  other.multiplier == multiplier &&
199
280
  other.retry_codes == retry_codes &&
200
- other.timeout == timeout
281
+ other.timeout == timeout &&
282
+ other.jitter == jitter &&
283
+ other.retry_predicate == retry_predicate
201
284
  end
202
285
  alias == eql?
203
286
 
204
287
  # @private Hash code
205
288
  def hash
206
- [initial_delay, max_delay, multiplier, retry_codes, timeout].hash
289
+ [initial_delay, max_delay, multiplier, retry_codes, timeout, jitter, retry_predicate].hash
207
290
  end
208
291
 
209
292
  private
210
293
 
211
294
  # @private
295
+ # Perform the currently calculated delay, adding a jitter.
296
+ #
212
297
  # @return [Numeric] The performed delay.
213
298
  def delay!
299
+ delay_to_perform = [delay + Kernel.rand(0.0..jitter), max_delay].min
214
300
  if @mock_time
215
- @mock_time += delay
216
- @mock_delay_callback&.call delay
301
+ @mock_time += delay_to_perform
302
+ @mock_delay_callback&.call delay_to_perform
217
303
  else
218
- Kernel.sleep delay
304
+ Kernel.sleep delay_to_perform
219
305
  end
220
306
  end
221
307
 
222
308
  # @private
223
- # @return [Numeric] The new delay in seconds.
309
+ # @return [Numeric] The new delay (sans jitter) in seconds.
224
310
  def increment_delay!
225
311
  @delay = [delay * multiplier, max_delay].min
226
312
  end
@@ -14,6 +14,6 @@
14
14
 
15
15
  module Gapic
16
16
  module Common
17
- VERSION = "1.0.0".freeze
17
+ VERSION = "1.6.1".freeze
18
18
  end
19
19
  end
@@ -183,7 +183,7 @@ module Gapic
183
183
  end
184
184
 
185
185
  def log_request request, metadata, try_number
186
- return request unless @stub_logger
186
+ return request unless @stub_logger&.enabled?
187
187
  @stub_logger.info do |entry|
188
188
  entry.set_system_name
189
189
  entry.set_service
@@ -221,7 +221,7 @@ module Gapic
221
221
  end
222
222
 
223
223
  def log_response response, try_number
224
- return response unless @stub_logger
224
+ return response unless @stub_logger&.enabled?
225
225
  @stub_logger.info do |entry|
226
226
  entry.set_system_name
227
227
  entry.set_service
@@ -42,6 +42,10 @@ module Gapic
42
42
  @kwargs = kwargs
43
43
  end
44
44
 
45
+ def enabled?
46
+ !!@logger
47
+ end
48
+
45
49
  def log severity
46
50
  return unless @logger
47
51
  locations = caller_locations
@@ -63,6 +67,10 @@ module Gapic
63
67
  log(Logger::DEBUG, &)
64
68
  end
65
69
 
70
+ def warn(&)
71
+ log(Logger::WARN, &)
72
+ end
73
+
66
74
  ##
67
75
  # @private
68
76
  # Builder for a log entry, passed to {StubLogger#log}.
@@ -196,12 +204,14 @@ module Gapic
196
204
  input
197
205
  when Class
198
206
  mod = input.name.split("::")[..-2].inject(Object) { |m, n| m.const_get n }
199
- if mod.const_defined? "Service"
200
- mod.const_get("Service").service_name
207
+ # inherit: false so a top-level ::Service is not mistaken for the
208
+ # generated gRPC Service sibling that REST stubs do not define.
209
+ if mod.const_defined? "Service", false
210
+ mod.const_get("Service", false).service_name
201
211
  else
202
212
  name_segments = input.name.split("::")[..-3]
203
213
  mod = name_segments.inject(Object) { |m, n| m.const_get n }
204
- name_segments.join "." if mod.const_defined? "Rest"
214
+ name_segments.join "." if mod.const_defined? "Rest", false
205
215
  end
206
216
  end
207
217
  end
@@ -38,13 +38,15 @@ module Gapic
38
38
  # @param multiplier [Numeric] The delay scaling factor for each subsequent retry attempt.
39
39
  # @param max_delay [Numeric] Maximum delay in seconds.
40
40
  # @param timeout [Numeric] Timeout threshold value in seconds.
41
+ # @param jitter [Numeric] Random jitter added to the delay in seconds.
41
42
  #
42
- def initialize initial_delay: nil, multiplier: nil, max_delay: nil, timeout: nil
43
+ def initialize initial_delay: nil, multiplier: nil, max_delay: nil, timeout: nil, jitter: nil
43
44
  super(
44
45
  initial_delay: initial_delay || DEFAULT_INITIAL_DELAY,
45
46
  max_delay: max_delay || DEFAULT_MAX_DELAY,
46
47
  multiplier: multiplier || DEFAULT_MULTIPLIER,
47
- timeout: timeout || DEFAULT_TIMEOUT
48
+ timeout: timeout || DEFAULT_TIMEOUT,
49
+ jitter: jitter
48
50
  )
49
51
  end
50
52
  end
@@ -278,7 +278,7 @@ module Gapic
278
278
  end
279
279
 
280
280
  def log_request method_name, request_id, try_number, body, metadata
281
- return unless stub_logger
281
+ return unless stub_logger&.enabled?
282
282
  stub_logger.info do |entry|
283
283
  entry.set_system_name
284
284
  entry.set_service
@@ -287,19 +287,29 @@ module Gapic
287
287
  entry.set "requestId", request_id
288
288
  entry.message = "Sending request to #{entry.service}.#{method_name} (try #{try_number})"
289
289
  end
290
- body = body.to_s
290
+ body_str = body.to_s
291
291
  metadata = metadata.to_h rescue {}
292
- return if body.empty? && metadata.empty?
292
+ return if body_str.empty? && metadata.empty?
293
293
  stub_logger.debug do |entry|
294
294
  entry.set "requestId", request_id
295
- entry.set "request", body
295
+ entry.set "request", abridge_request_body(body_str)
296
296
  entry.set "headers", metadata
297
297
  entry.message = "(request payload as JSON)"
298
298
  end
299
299
  end
300
300
 
301
+ def abridge_request_body body_str
302
+ utf8_body = body_str.dup.force_encoding Encoding::UTF_8
303
+ if body_str.bytesize > 1024 || !utf8_body.valid_encoding?
304
+ prefix_hex = body_str.byteslice(0, 32).unpack1 "H*"
305
+ "<#{body_str.bytesize} bytes, first 32: #{prefix_hex}>"
306
+ else
307
+ utf8_body
308
+ end
309
+ end
310
+
301
311
  def log_response method_name, request_id, try_number, response, is_server_streaming
302
- return unless stub_logger
312
+ return unless stub_logger&.enabled?
303
313
  stub_logger.info do |entry|
304
314
  entry.set_system_name
305
315
  entry.set_service
@@ -22,6 +22,9 @@ module Gapic
22
22
  module Rest
23
23
  # Gapic REST exception class
24
24
  class Error < ::Gapic::Common::Error
25
+ # @private
26
+ REST_ERROR_PREFIX = "An error has occurred when making a REST request".freeze
27
+
25
28
  # @return [Integer, nil] the http status code for the error
26
29
  attr_reader :status_code
27
30
  # @return [Object, nil] the text representation of status as parsed from the response body
@@ -79,7 +82,7 @@ module Gapic
79
82
 
80
83
  if err.response_body
81
84
  msg, code, status, details = try_parse_from_body err.response_body
82
- message = "An error has occurred when making a REST request: #{msg}" unless msg.nil?
85
+ message = "#{REST_ERROR_PREFIX}: #{msg}" unless msg.nil?
83
86
  status_code = code unless code.nil?
84
87
  end
85
88
 
@@ -111,12 +111,14 @@ module Gapic
111
111
  # @return [Hash{String, String}]
112
112
  # Name to value hash of the variables for the uri template expansion.
113
113
  # The values are percent-escaped with slashes potentially preserved.
114
+ # @raise [Gapic::Common::Error] If any parameter value fails path traversal validation.
114
115
  def bind_uri_values! http_binding, request_hash
115
116
  http_binding.field_bindings.to_h do |field_binding|
116
117
  field_path_camel = field_binding.field_path.split(".").map { |part| camel_name_for part }.join(".")
117
118
  field_value = extract_scalar_value! request_hash, field_path_camel, field_binding.regex
118
119
 
119
120
  if field_value
121
+ validate_field_binding! field_binding, field_value
120
122
  field_value = field_value.split("/").map { |segment| percent_escape segment }.join("/")
121
123
  end
122
124
 
@@ -124,6 +126,43 @@ module Gapic
124
126
  end
125
127
  end
126
128
 
129
+ # Validates a user-supplied parameter value bound to a standard (*) or path (**) URI template variable
130
+ # to prevent directory traversal exploits.
131
+ #
132
+ # @param field_binding [HttpBinding::FieldBinding] The field binding template metadata.
133
+ # @param field_value [String] The parameter value to validate.
134
+ # @raise [Gapic::Common::Error] If validation fails.
135
+ def validate_field_binding! field_binding, field_value
136
+ validate_path_binding! field_binding, field_value
137
+ end
138
+
139
+ # Validates standard (*) and path (**) parameters by ensuring that no segment in the parameter
140
+ # value is a directory traversal segment (. or ..).
141
+ #
142
+ # Validation Mechanism:
143
+ # 1. Splits the parameter value by slash (`/`) using `-1` limit to preserve all segments.
144
+ # 2. Checks each segment. If any segment matches `.` or `..`, it immediately raises
145
+ # a `Gapic::Common::Error`, aborting the request.
146
+ # 3. Empty segments (e.g. duplicate slashes `//` or trailing slashes `/`) are allowed
147
+ # by this validator and passed to the server, which handles normalization or returns 400.
148
+ #
149
+ # @param field_binding [HttpBinding::FieldBinding] The field binding template metadata.
150
+ # @param field_value [String] The parameter value to validate.
151
+ # @raise [Gapic::Common::Error] If validation fails.
152
+ def validate_path_binding! field_binding, field_value
153
+ segments = field_value.split("/", -1)
154
+ segments.each do |segment|
155
+ next unless [".", ".."].include? segment
156
+ if field_binding.preserve_slashes
157
+ raise ::Gapic::Common::Error,
158
+ "Value for #{field_binding.field_path} must not contain segments that are exactly '#{segment}'."
159
+ else
160
+ raise ::Gapic::Common::Error,
161
+ "Invalid value for #{field_binding.field_path} '#{segment}'."
162
+ end
163
+ end
164
+ end
165
+
127
166
  # Percent-escapes a string.
128
167
  # @param str [String] String to escape.
129
168
  # @return [String] Escaped string.
@@ -160,7 +199,16 @@ module Gapic
160
199
  request_body_field = request.send body_template.to_sym if request.respond_to? body_template.to_sym
161
200
  if request_body_field
162
201
  request_hash_without_uri.delete camel_name_for body_template
163
- body = request_body_field.to_json emit_defaults: true
202
+ # `emit_defaults` is only meaningful for, and only accepted by,
203
+ # `Google::Protobuf::MessageExts#to_json`. When the body template points at a
204
+ # scalar, enum or repeated field, `to_json` resolves to the json gem's
205
+ # `Object#to_json`, which has never accepted the keyword: json 2.x silently
206
+ # discarded unknown keywords, json 3.x raises ArgumentError.
207
+ body = if request_body_field.is_a? ::Google::Protobuf::MessageExts
208
+ request_body_field.to_json emit_defaults: true
209
+ else
210
+ request_body_field.to_json
211
+ end
164
212
  end
165
213
 
166
214
  query_params = build_query_params request_hash_without_uri
@@ -204,7 +252,7 @@ module Gapic
204
252
  # Returns nil if:
205
253
  # - the field is not found
206
254
  # - the field is a Message or an array,
207
- # - the regex does not match
255
+ # - the regex does not match the entire string representation
208
256
  # @param request_hash [Hash]
209
257
  # A hash of the GRPC request or the sub-request with the unset
210
258
  # proto3_optional fields removed.
@@ -218,7 +266,9 @@ module Gapic
218
266
 
219
267
  # Covers the case where in `foo.bar.baz`, `baz` is still a submessage or an array.
220
268
  return nil if value.is_a?(::Hash) || value.is_a?(::Array)
221
- value.to_s if value.to_s =~ regex
269
+ str = value.to_s
270
+ match = regex.match str
271
+ str if match && match.pre_match.empty? && match.post_match.empty?
222
272
  end
223
273
 
224
274
  # Finds a value in the hash by path.
@@ -0,0 +1,48 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ require "gapic/config"
16
+
17
+ module Gapic
18
+ module Rest
19
+ ##
20
+ # @private
21
+ # A specialized Configuration class to use when generating
22
+ # package-level binding override configuration.
23
+ #
24
+ # This configuration is for internal use of the client library classes,
25
+ # and it is not intended that the end-users will read or change it.
26
+ #
27
+ # @attribute [rw] bindings_override
28
+ # Overrides for http bindings for the RPC of the mixins for the given package.
29
+ # return [::Hash{::Symbol=>::Array<::Gapic::Rest::GrpcTranscoder::HttpBinding>}]
30
+ #
31
+ class HttpBindingOverrideConfiguration
32
+ extend ::Gapic::Config
33
+
34
+ # @private
35
+ # Overrides for http bindings for the RPC of the mixins for the given package.
36
+ # Services in the package should use these when creating clients for the mixin services.
37
+ # @return [::Hash{::Symbol=>::Array<::Gapic::Rest::GrpcTranscoder::HttpBinding>}]
38
+ config_attr :bindings_override, {}, ::Hash, nil
39
+
40
+ # @private
41
+ def initialize parent_config = nil
42
+ @parent_config = parent_config unless parent_config.nil?
43
+
44
+ yield self if block_given?
45
+ end
46
+ end
47
+ end
48
+ end