bson 5.2.0-java → 5.2.1-java

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,163 @@
1
+ # rubocop:todo all
2
+ # Copyright (C) 2020 MongoDB Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ require "spec_helper"
17
+
18
+ describe BSON::DbPointer do
19
+
20
+ let(:ref) { 'db.coll' }
21
+ let(:id) { BSON::ObjectId.from_string('56e1fc72e0c917e9c4714161') }
22
+ let(:object) { described_class.new(ref, id) }
23
+
24
+ describe "#initialize" do
25
+
26
+ it "stores the ref and the id" do
27
+ expect(object.ref).to eq(ref)
28
+ expect(object.id).to eq(id)
29
+ end
30
+
31
+ # RUBY-3936. The DBPointer wire format is a string followed by exactly 12
32
+ # raw bytes, and #to_bson writes the id duck-typed. An id of any other type
33
+ # emits the wrong number of bytes, which reframes the enclosing document
34
+ # for every conforming reader. Reject it at construction instead.
35
+ context "when the id is not an ObjectId" do
36
+
37
+ [
38
+ [ 'a binary', BSON::Binary.new('12345678901234567890', :generic) ],
39
+ [ 'a string', '56e1fc72e0c917e9c4714161' ],
40
+ [ 'a hash', { 'a' => 1 } ],
41
+ [ 'an integer', 1 ],
42
+ [ 'nil', nil ],
43
+ ].each do |desc, bad_id|
44
+
45
+ context "when the id is #{desc}" do
46
+
47
+ it "raises an error" do
48
+ expect do
49
+ described_class.new(ref, bad_id)
50
+ end.to raise_error(ArgumentError, /id must be a BSON::ObjectId/)
51
+ end
52
+ end
53
+ end
54
+ end
55
+
56
+ context "when the ref is not a string" do
57
+
58
+ [
59
+ [ 'nil', nil ],
60
+ [ 'an integer', 5 ],
61
+ [ 'a symbol', :coll ],
62
+ ].each do |desc, bad_ref|
63
+
64
+ context "when the ref is #{desc}" do
65
+
66
+ it "raises an error" do
67
+ expect do
68
+ described_class.new(bad_ref, id)
69
+ end.to raise_error(ArgumentError, /ref must be a String/)
70
+ end
71
+ end
72
+ end
73
+ end
74
+ end
75
+
76
+ describe "#==" do
77
+
78
+ context "when the objects are equal" do
79
+ let(:other) { described_class.new(ref, id) }
80
+
81
+ it "returns true" do
82
+ expect(object).to eq(other)
83
+ end
84
+ end
85
+
86
+ context "when the refs are not equal" do
87
+ let(:other) { described_class.new('db.other', id) }
88
+
89
+ it "returns false" do
90
+ expect(object).to_not eq(other)
91
+ end
92
+ end
93
+
94
+ context "when the ids are not equal" do
95
+ let(:other) { described_class.new(ref, BSON::ObjectId.new) }
96
+
97
+ it "returns false" do
98
+ expect(object).to_not eq(other)
99
+ end
100
+ end
101
+
102
+ context "when the other object is not a DbPointer" do
103
+
104
+ it "returns false" do
105
+ expect(object).to_not eq('foo')
106
+ end
107
+ end
108
+ end
109
+
110
+ describe "#as_extended_json" do
111
+
112
+ it "returns the canonical extended json representation" do
113
+ expect(object.as_extended_json).to eq(
114
+ { '$dbPointer' => { '$ref' => ref, '$id' => { '$oid' => '56e1fc72e0c917e9c4714161' } } }
115
+ )
116
+ end
117
+
118
+ it_behaves_like 'an Extended JSON serializable object'
119
+ it_behaves_like '#as_json calls #as_extended_json'
120
+ end
121
+
122
+ describe "#to_bson" do
123
+
124
+ let(:type) { 12.chr }
125
+ let(:obj) { object }
126
+ let(:bson) do
127
+ "#{(ref.length + 1).to_bson.to_s}#{ref}#{BSON::NULL_BYTE}#{id.to_bson.to_s}"
128
+ end
129
+
130
+ it_behaves_like "a bson element"
131
+ it_behaves_like "a serializable bson element"
132
+
133
+ it "writes exactly twelve bytes for the id" do
134
+ encoded = obj.to_bson.to_s
135
+ expect(encoded.bytesize - (4 + ref.length + 1)).to eq(12)
136
+ end
137
+ end
138
+
139
+ describe "#from_bson" do
140
+
141
+ let(:type) { 12.chr }
142
+ let(:obj) { object }
143
+ let(:bson) do
144
+ "#{(ref.length + 1).to_bson.to_s}#{ref}#{BSON::NULL_BYTE}#{id.to_bson.to_s}"
145
+ end
146
+
147
+ it_behaves_like "a deserializable bson element"
148
+ end
149
+
150
+ describe "round trip through a document" do
151
+
152
+ # RUBY-3936. Guards the framing itself: a document containing a DBPointer
153
+ # must read back with exactly the keys the application wrote, with no
154
+ # extra elements recovered from a mis-sized id.
155
+ it "reads back only the fields that were written" do
156
+ doc = BSON::Document.new('a' => object, 'z' => 1)
157
+ round = BSON::Document.from_bson(BSON::ByteBuffer.new(doc.to_bson.to_s))
158
+ expect(round.keys).to eq([ 'a', 'z' ])
159
+ expect(round['a']).to eq(object)
160
+ expect(round['z']).to eq(1)
161
+ end
162
+ end
163
+ end
@@ -51,7 +51,7 @@ describe BSON::Decimal128 do
51
51
  end
52
52
 
53
53
  let(:expected_bson) do
54
- [expected_low_bits].pack(BSON::Int64::PACK) + [expected_high_bits].pack(BSON::Int64::PACK)
54
+ [expected_low_bits].pack(PackDirectives::INT64) + [expected_high_bits].pack(PackDirectives::INT64)
55
55
  end
56
56
 
57
57
  it 'sets the correct high order bits' do
@@ -343,4 +343,118 @@ describe "BSON::ExtJSON.parse" do
343
343
  end
344
344
  end
345
345
  end
346
+
347
+ context 'when input is a DBPointer' do
348
+
349
+ context 'when $id is an ObjectId' do
350
+ let(:input) do
351
+ { '$dbPointer' => { '$ref' => 'coll', '$id' => { '$oid' => '56e1fc72e0c917e9c4714161' } } }
352
+ end
353
+
354
+ it 'returns a BSON::DbPointer instance' do
355
+ expect(parsed).to be_a(BSON::DbPointer)
356
+ expect(parsed.ref).to eq('coll')
357
+ expect(parsed.id).to eq(BSON::ObjectId.from_string('56e1fc72e0c917e9c4714161'))
358
+ end
359
+ end
360
+
361
+ context 'when $id is a binary' do
362
+ let(:input) do
363
+ { '$dbPointer' => { '$ref' => 'coll',
364
+ '$id' => { '$binary' => { 'base64' => '//8=', 'subType' => '00' } } } }
365
+ end
366
+
367
+ it 'raises an exception' do
368
+ expect do
369
+ parsed
370
+ end.to raise_error(BSON::Error::ExtJSONParseError, /\$id must be an ObjectId/)
371
+ end
372
+ end
373
+
374
+ context 'when $id is a plain object' do
375
+ let(:input) do
376
+ { '$dbPointer' => { '$ref' => 'coll', '$id' => { 'a' => 1 } } }
377
+ end
378
+
379
+ it 'raises an exception' do
380
+ expect do
381
+ parsed
382
+ end.to raise_error(BSON::Error::ExtJSONParseError, /\$id must be an ObjectId/)
383
+ end
384
+ end
385
+
386
+ context 'when $id is an integer' do
387
+ let(:input) do
388
+ { '$dbPointer' => { '$ref' => 'coll', '$id' => { '$numberInt' => '1' } } }
389
+ end
390
+
391
+ it 'raises an exception' do
392
+ expect do
393
+ parsed
394
+ end.to raise_error(BSON::Error::ExtJSONParseError, /\$id must be an ObjectId/)
395
+ end
396
+ end
397
+
398
+ context 'when $id is a hex string rather than an $oid wrapper' do
399
+ let(:input) do
400
+ { '$dbPointer' => { '$ref' => 'coll', '$id' => '56e1fc72e0c917e9c4714161' } }
401
+ end
402
+
403
+ it 'raises a parse error rather than a NoMethodError' do
404
+ expect do
405
+ parsed
406
+ end.to raise_error(BSON::Error::ExtJSONParseError, /\$id must be an ObjectId/)
407
+ end
408
+ end
409
+
410
+ context 'when $ref is null' do
411
+ let(:input) do
412
+ { '$dbPointer' => { '$ref' => nil, '$id' => { '$oid' => '56e1fc72e0c917e9c4714161' } } }
413
+ end
414
+
415
+ it 'raises a parse error rather than a NoMethodError' do
416
+ expect do
417
+ parsed
418
+ end.to raise_error(BSON::Error::ExtJSONParseError, /\$ref must be a string/)
419
+ end
420
+ end
421
+
422
+ context 'when $ref is not a string' do
423
+ let(:input) do
424
+ { '$dbPointer' => { '$ref' => 5, '$id' => { '$oid' => '56e1fc72e0c917e9c4714161' } } }
425
+ end
426
+
427
+ it 'raises a parse error rather than a NoMethodError' do
428
+ expect do
429
+ parsed
430
+ end.to raise_error(BSON::Error::ExtJSONParseError, /\$ref must be a string/)
431
+ end
432
+ end
433
+
434
+ # RUBY-3936. The DBPointer wire format is a string followed by exactly 12
435
+ # raw bytes. A $binary id makes DbPointer#to_bson emit an int32 length, a
436
+ # subtype byte and a payload of any length instead. A conforming reader
437
+ # consumes 12 of those bytes and reads whatever follows as further elements
438
+ # of the enclosing document, so the value escapes its own slot: the payload
439
+ # below is 7 bytes of filler followed by a forged int32 element named
440
+ # "injected". Before this was validated, the document serialized from this
441
+ # input read back as {"a" => ..., "injected" => 42}.
442
+ context 'when $id is a binary crafted to reframe the enclosing document' do
443
+ let(:payload) do
444
+ ("\x00" * 7) + "\x10injected\x00" + [ 42 ].pack('l<')
445
+ end
446
+
447
+ let(:input) do
448
+ { 'a' => { '$dbPointer' => { '$ref' => 'coll',
449
+ '$id' => { '$binary' => { 'base64' => Base64.strict_encode64(payload),
450
+ 'subType' => '00' } } } } }
451
+ end
452
+
453
+ it 'rejects the input instead of emitting a document with forged fields' do
454
+ expect do
455
+ parsed
456
+ end.to raise_error(BSON::Error::ExtJSONParseError, /\$id must be an ObjectId/)
457
+ end
458
+ end
459
+ end
346
460
  end
@@ -21,7 +21,7 @@ describe Float do
21
21
 
22
22
  let(:type) { 1.chr }
23
23
  let(:obj) { 1.2332 }
24
- let(:bson) { [ obj ].pack(Float::PACK) }
24
+ let(:bson) { [ obj ].pack(PackDirectives::FLOAT) }
25
25
 
26
26
  it_behaves_like "a bson element"
27
27
  it_behaves_like "a serializable bson element"
@@ -67,7 +67,7 @@ describe BSON::Int32 do
67
67
 
68
68
  let(:type) { 16.chr }
69
69
  let(:obj) { 123 }
70
- let(:bson) { [ obj ].pack(BSON::Int32::PACK) }
70
+ let(:bson) { [ obj ].pack(PackDirectives::INT32) }
71
71
 
72
72
  it_behaves_like "a bson element"
73
73
  it_behaves_like "a deserializable bson element"
@@ -76,9 +76,9 @@ describe BSON::Int32 do
76
76
  describe "when the integer is negative" do
77
77
 
78
78
  let(:decoded) { -1 }
79
- let(:encoded) { BSON::ByteBuffer.new([ -1 ].pack(BSON::Int32::PACK)) }
79
+ let(:encoded) { BSON::ByteBuffer.new([ -1 ].pack(PackDirectives::INT32)) }
80
80
  let(:decoded_2) { -50 }
81
- let(:encoded_2) { BSON::ByteBuffer.new([ -50 ].pack(BSON::Int32::PACK)) }
81
+ let(:encoded_2) { BSON::ByteBuffer.new([ -50 ].pack(PackDirectives::INT32)) }
82
82
 
83
83
  it "decodes a -1 correctly" do
84
84
  expect(BSON::Int32.from_bson(encoded)).to eq(decoded)
@@ -95,7 +95,7 @@ describe BSON::Int32 do
95
95
 
96
96
  let(:type) { 16.chr }
97
97
  let(:obj) { BSON::Int32.new(Integer::MAX_32BIT - 1) }
98
- let(:bson) { [ Integer::MAX_32BIT - 1 ].pack(BSON::Int32::PACK) }
98
+ let(:bson) { [ Integer::MAX_32BIT - 1 ].pack(PackDirectives::INT32) }
99
99
 
100
100
  it_behaves_like "a serializable bson element"
101
101
  end
@@ -67,7 +67,7 @@ describe BSON::Int64 do
67
67
 
68
68
  let(:type) { 18.chr }
69
69
  let(:obj) { 1325376000000 }
70
- let(:bson) { [ obj ].pack(BSON::Int64::PACK) }
70
+ let(:bson) { [ obj ].pack(PackDirectives::INT64) }
71
71
 
72
72
  it_behaves_like "a bson element"
73
73
  it_behaves_like "a deserializable bson element"
@@ -139,7 +139,7 @@ describe BSON::Int64 do
139
139
 
140
140
  let(:type) { 18.chr }
141
141
  let(:obj) { BSON::Int64.new(Integer::MAX_64BIT - 1) }
142
- let(:bson) { [ Integer::MAX_64BIT - 1 ].pack(BSON::Int64::PACK) }
142
+ let(:bson) { [ Integer::MAX_64BIT - 1 ].pack(PackDirectives::INT64) }
143
143
 
144
144
  it_behaves_like "a serializable bson element"
145
145
  end
@@ -23,7 +23,7 @@ describe Integer do
23
23
 
24
24
  let(:type) { 16.chr }
25
25
  let(:obj) { Integer::MAX_32BIT - 1 }
26
- let(:bson) { [ obj ].pack(BSON::Int32::PACK) }
26
+ let(:bson) { [ obj ].pack(PackDirectives::INT32) }
27
27
 
28
28
  it_behaves_like "a serializable bson element"
29
29
  end
@@ -32,7 +32,7 @@ describe Integer do
32
32
 
33
33
  let(:type) { 18.chr }
34
34
  let(:obj) { Integer::MAX_64BIT - 1 }
35
- let(:bson) { [ obj ].pack(BSON::Int64::PACK) }
35
+ let(:bson) { [ obj ].pack(PackDirectives::INT64) }
36
36
 
37
37
  it_behaves_like "a serializable bson element"
38
38
  end
@@ -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"