bson 5.2.0 → 5.2.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.
@@ -0,0 +1,198 @@
1
+ # frozen_string_literal: true
2
+ # rubocop:todo all
3
+ # Copyright (C) 2026 MongoDB Inc.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ require "spec_helper"
18
+
19
+ describe "BSON nesting depth limit" do
20
+ # On JRuby, very deep recursion may overflow the JVM thread stack before
21
+ # our depth counter fires (each Ruby method invocation inflates to multiple
22
+ # JVM frames). Either outcome — BSON::Error::BSONDecodeError or a JVM
23
+ # StackOverflowError — means the process did not crash.
24
+ #
25
+ # The Java throwable is not a subclass of Ruby's Exception, so we rescue it
26
+ # by reference. On MRI it is replaced with an unreachable sentinel.
27
+ java_stack_overflow = if defined?(JRUBY_VERSION)
28
+ eval('Java::JavaLang::StackOverflowError')
29
+ else
30
+ Class.new(Exception)
31
+ end
32
+
33
+ matcher :raise_decode_error_or_stack_overflow do
34
+ supports_block_expectations
35
+ match do |block|
36
+ begin
37
+ block.call
38
+ false
39
+ rescue BSON::Error::BSONDecodeError, SystemStackError, java_stack_overflow
40
+ true
41
+ end
42
+ end
43
+ end
44
+
45
+
46
+ # Build a BSON byte string with exactly n nested documents:
47
+ # n=1 -> {} (5 bytes), n=2 -> {a: {}}, n=3 -> {a: {a: {}}}, ...
48
+ # Each wrapping level adds 8 bytes of overhead:
49
+ # int32 length(4) + type(1) + cstring "a\0"(2) + ... + terminator(1)
50
+ # Innermost empty subdoc is 5 bytes.
51
+ def deeply_nested_bson(n)
52
+ wrappers = n - 1
53
+ total = 5 + wrappers * 8
54
+ buf = String.new(capacity: total).force_encoding("BINARY")
55
+ remaining = total
56
+ wrappers.times do
57
+ buf << [remaining].pack("V")
58
+ buf << "\x03".b
59
+ buf << "a\x00".b
60
+ remaining -= 8
61
+ end
62
+ buf << "\x05\x00\x00\x00\x00".b
63
+ wrappers.times { buf << "\x00".b }
64
+ buf
65
+ end
66
+
67
+ # Build a BSON byte string with exactly n nested arrays: [], [[]], [[[]]]...
68
+ # Each wrapping level: int32(4) + type 0x04(1) + cstring "0\0"(2) + ... + 0x00(1) = 8.
69
+ def deeply_nested_array_bson(n)
70
+ wrappers = n - 1
71
+ total = 5 + wrappers * 8
72
+ buf = String.new(capacity: total).force_encoding("BINARY")
73
+ remaining = total
74
+ wrappers.times do
75
+ buf << [remaining].pack("V")
76
+ buf << "\x04".b
77
+ buf << "0\x00".b
78
+ remaining -= 8
79
+ end
80
+ buf << "\x05\x00\x00\x00\x00".b
81
+ wrappers.times { buf << "\x00".b }
82
+ buf
83
+ end
84
+
85
+ describe "Hash.from_bson" do
86
+ context "when nesting is at the maximum depth" do
87
+ let(:bytes) { deeply_nested_bson(BSON::MAX_NESTING_DEPTH) }
88
+
89
+ it "decodes successfully" do
90
+ expect {
91
+ Hash.from_bson(BSON::ByteBuffer.new(bytes))
92
+ }.not_to raise_error
93
+ end
94
+ end
95
+
96
+ context "when nesting exceeds the maximum depth" do
97
+ let(:bytes) { deeply_nested_bson(BSON::MAX_NESTING_DEPTH + 1) }
98
+
99
+ it "raises BSONDecodeError" do
100
+ expect {
101
+ Hash.from_bson(BSON::ByteBuffer.new(bytes))
102
+ }.to raise_error(BSON::Error::BSONDecodeError, /nesting/i)
103
+ end
104
+ end
105
+
106
+ context "when nesting is far beyond the maximum (DoS payload)" do
107
+ let(:bytes) { deeply_nested_bson(100_000) }
108
+
109
+ it "raises a decode error or stack overflow without crashing the process" do
110
+ expect {
111
+ Hash.from_bson(BSON::ByteBuffer.new(bytes))
112
+ }.to raise_decode_error_or_stack_overflow
113
+ end
114
+ end
115
+ end
116
+
117
+ describe "Array.from_bson via Hash" do
118
+ context "when array nesting exceeds the maximum depth" do
119
+ # Wrap deep arrays inside a single hash so we go through the registered
120
+ # types path: { a: [ [ [ ... ] ] ] }
121
+ let(:bytes) do
122
+ inner = deeply_nested_array_bson(BSON::MAX_NESTING_DEPTH + 1)
123
+ # Wrap: int32 len + 0x04(array) + "a\0" + inner + 0x00
124
+ len = 4 + 1 + 2 + inner.bytesize + 1
125
+ out = String.new(capacity: len).force_encoding("BINARY")
126
+ out << [len].pack("V")
127
+ out << "\x04".b
128
+ out << "a\x00".b
129
+ out << inner
130
+ out << "\x00".b
131
+ out
132
+ end
133
+
134
+ it "raises BSONDecodeError" do
135
+ expect {
136
+ Hash.from_bson(BSON::ByteBuffer.new(bytes))
137
+ }.to raise_error(BSON::Error::BSONDecodeError, /nesting/i)
138
+ end
139
+ end
140
+ end
141
+
142
+ describe "BSON::ExtJSON.parse_obj" do
143
+ # Build a Ruby structure with exactly n levels of hash nesting:
144
+ # n=1 -> {}, n=2 -> {a: {}}, n=3 -> {a: {a: {}}}, ...
145
+ def deeply_nested_hash(n)
146
+ h = {}
147
+ cur = h
148
+ (n - 1).times { cur["a"] = nxt = {}; cur = nxt }
149
+ h
150
+ end
151
+
152
+ # Same for arrays: n=1 -> [], n=2 -> [[]], ...
153
+ def deeply_nested_array(n)
154
+ a = []
155
+ cur = a
156
+ (n - 1).times { cur << (nxt = []); cur = nxt }
157
+ a
158
+ end
159
+
160
+ context "when hash nesting is at the maximum depth" do
161
+ let(:input) { deeply_nested_hash(BSON::MAX_NESTING_DEPTH) }
162
+
163
+ it "parses successfully" do
164
+ expect { BSON::ExtJSON.parse_obj(input) }.not_to raise_error
165
+ end
166
+ end
167
+
168
+ context "when hash nesting exceeds the maximum depth" do
169
+ let(:input) { deeply_nested_hash(BSON::MAX_NESTING_DEPTH + 1) }
170
+
171
+ it "raises BSONDecodeError" do
172
+ expect {
173
+ BSON::ExtJSON.parse_obj(input)
174
+ }.to raise_error(BSON::Error::BSONDecodeError, /nesting/i)
175
+ end
176
+ end
177
+
178
+ context "when array nesting exceeds the maximum depth" do
179
+ let(:input) { deeply_nested_array(BSON::MAX_NESTING_DEPTH + 1) }
180
+
181
+ it "raises BSONDecodeError" do
182
+ expect {
183
+ BSON::ExtJSON.parse_obj(input)
184
+ }.to raise_error(BSON::Error::BSONDecodeError, /nesting/i)
185
+ end
186
+ end
187
+
188
+ context "when nesting is far beyond the maximum (DoS payload)" do
189
+ let(:input) { deeply_nested_hash(50_000) }
190
+
191
+ it "raises a decode error or stack overflow without crashing the process" do
192
+ expect {
193
+ BSON::ExtJSON.parse_obj(input)
194
+ }.to raise_decode_error_or_stack_overflow
195
+ end
196
+ end
197
+ end
198
+ end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright (C) 2026 MongoDB Inc.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ require 'spec_helper'
18
+
19
+ # Tests for the fix of RUBY-3894: Heap Buffer Overflow in put_string.
20
+ #
21
+ # BSON encodes string lengths as int32_t. A Ruby string longer than INT32_MAX
22
+ # bytes caused a silent integer truncation in the C extension, which then
23
+ # passed the resulting negative value to the UTF-8 validator as size_t, wrapping
24
+ # to near UINT64_MAX and driving reads far past the heap allocation.
25
+ #
26
+ # These tests require approximately 2 GB of free memory and only run when
27
+ # STRESS=1 is set in the environment. They are also MRI-only because the bug
28
+ # lives in the C native extension.
29
+ describe 'BSON string length overflow protection' do
30
+ before(:all) do
31
+ skip 'C native extension not used on JRuby' if BSON::Environment.jruby?
32
+ skip 'Set STRESS=1 to run tests that require ~2 GB of free memory' unless ENV['STRESS'] == '1'
33
+ end
34
+
35
+ let(:buffer) { BSON::ByteBuffer.new }
36
+
37
+ # 2**31 bytes is one byte past INT32_MAX, which is the smallest input that
38
+ # triggers the int32_t truncation.
39
+ let(:huge_string) { 'A' * (2**31) }
40
+
41
+ describe '#put_string' do
42
+ it 'raises ArgumentError instead of overflowing' do
43
+ expect do
44
+ buffer.put_string(huge_string)
45
+ end.to raise_error(ArgumentError, /String length \d+ exceeds BSON maximum/)
46
+ end
47
+ end
48
+
49
+ describe '#put_cstring' do
50
+ it 'raises ArgumentError instead of overflowing' do
51
+ expect do
52
+ buffer.put_cstring(huge_string)
53
+ end.to raise_error(ArgumentError, /String length \d+ exceeds BSON maximum/)
54
+ end
55
+ end
56
+
57
+ describe '#put_symbol' do
58
+ it 'raises ArgumentError instead of overflowing' do
59
+ expect do
60
+ buffer.put_symbol(huge_string.to_sym)
61
+ end.to raise_error(ArgumentError, /String length \d+ exceeds BSON maximum/)
62
+ end
63
+ end
64
+ end
@@ -28,7 +28,7 @@ describe Time do
28
28
  context "when the time has no microseconds" do
29
29
 
30
30
  let(:obj) { Time.utc(2012, 1, 1, 0, 0, 0) }
31
- let(:bson) { [ (obj.to_i * 1000) + (obj.usec / 1000) ].pack(BSON::Int64::PACK) }
31
+ let(:bson) { [ (obj.to_i * 1000) + (obj.usec / 1000) ].pack(PackDirectives::INT64) }
32
32
 
33
33
  it_behaves_like "a serializable bson element"
34
34
  it_behaves_like "a deserializable bson element"
@@ -37,7 +37,7 @@ describe Time do
37
37
  context "when the time has microseconds" do
38
38
 
39
39
  let(:obj) { Time.at(Time.utc(2014, 03, 22, 18, 05, 05).to_i, 505000).utc }
40
- let(:bson) { [ (obj.to_i * 1000) + (obj.usec / 1000) ].pack(BSON::Int64::PACK) }
40
+ let(:bson) { [ (obj.to_i * 1000) + (obj.usec / 1000) ].pack(PackDirectives::INT64) }
41
41
 
42
42
  it_behaves_like "a serializable bson element"
43
43
  it_behaves_like "a deserializable bson element"
@@ -47,7 +47,7 @@ describe Time do
47
47
  context "when the time precedes epoch" do
48
48
 
49
49
  let(:obj) { Time.utc(1969, 1, 1, 0, 0, 0) }
50
- let(:bson) { [ (obj.to_f * 1000).to_i ].pack(BSON::Int64::PACK) }
50
+ let(:bson) { [ (obj.to_f * 1000).to_i ].pack(PackDirectives::INT64) }
51
51
 
52
52
  it_behaves_like "a serializable bson element"
53
53
  it_behaves_like "a deserializable bson element"
@@ -50,7 +50,7 @@ context 'when ActiveSupport support is enabled' do
50
50
  context "when the TimeWithZone is not in UTC" do
51
51
 
52
52
  let(:obj) { Time.utc(2012, 12, 12, 0, 0, 0).in_time_zone("Pacific Time (US & Canada)") }
53
- let(:bson) { [ (obj.utc.to_f * 1000).to_i ].pack(BSON::Int64::PACK) }
53
+ let(:bson) { [ (obj.utc.to_f * 1000).to_i ].pack(PackDirectives::INT64) }
54
54
 
55
55
  it_behaves_like "a serializable bson element"
56
56
  it_behaves_like 'deserializes as expected'
@@ -59,7 +59,7 @@ context 'when ActiveSupport support is enabled' do
59
59
  context "when the TimeWithZone is in UTC" do
60
60
 
61
61
  let(:obj) { Time.utc(2012, 1, 1, 0, 0, 0).in_time_zone("UTC") }
62
- let(:bson) { [ (obj.utc.to_f * 1000).to_i ].pack(BSON::Int64::PACK) }
62
+ let(:bson) { [ (obj.utc.to_f * 1000).to_i ].pack(PackDirectives::INT64) }
63
63
 
64
64
  it_behaves_like "a serializable bson element"
65
65
  it_behaves_like 'deserializes as expected'
@@ -121,7 +121,7 @@ describe BSON::Timestamp do
121
121
 
122
122
  let(:type) { 17.chr }
123
123
  let(:obj) { described_class.new(1, 10) }
124
- let(:bson) { [ 10, 1 ].pack(BSON::Int32::PACK * 2) }
124
+ let(:bson) { [ 10, 1 ].pack(PackDirectives::INT32 * 2) }
125
125
 
126
126
  it_behaves_like "a bson element"
127
127
  it_behaves_like "a serializable bson element"
data/spec/bson_spec.rb CHANGED
@@ -19,11 +19,23 @@ describe BSON do
19
19
 
20
20
  describe ".ObjectId" do
21
21
 
22
- let(:string) { "4e4d66343b39b68407000001" }
22
+ context 'when given a string' do
23
+ let(:string) { "4e4d66343b39b68407000001" }
23
24
 
24
- it "returns an BSON::ObjectId from given string" do
25
- expect(described_class::ObjectId(string)).to be_a BSON::ObjectId
26
- expect(described_class::ObjectId(string)).to eq BSON::ObjectId.from_string(string)
25
+ it "returns a BSON::ObjectId from given string" do
26
+ expect(described_class::ObjectId(string)).to be_a BSON::ObjectId
27
+ expect(described_class::ObjectId(string)).to eq BSON::ObjectId.from_string(string)
28
+ end
29
+ end
30
+
31
+ context 'when given an object id' do
32
+ let(:object_id) do
33
+ described_class::ObjectId.new
34
+ end
35
+
36
+ it 'returns the same object' do
37
+ expect(described_class::ObjectId(object_id)).to be(object_id)
38
+ end
27
39
  end
28
40
  end
29
41
 
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Pack directives used by the test suite to build reference BSON encodings.
4
+ #
5
+ # These mirror the (now deprecated) BSON::Float::PACK, BSON::Int32::PACK, and
6
+ # BSON::Int64::PACK constants. The library no longer uses those constants
7
+ # internally, so the specs keep their own copies here rather than depending on
8
+ # deprecated production constants.
9
+ module PackDirectives
10
+ # Pack directive for 8 byte floating points.
11
+ FLOAT = 'E'
12
+
13
+ # Pack directive for little-endian 32 bit integers.
14
+ INT32 = 'l<'
15
+
16
+ # Pack directive for little-endian 64 bit integers.
17
+ INT64 = 'q<'
18
+ end