Skip to content

Commit 216a913

Browse files
author
Divjot Arora
authored
GODRIVER-1504 Restrict top-level keys from being parsed as extjson (#340)
1 parent d080bd0 commit 216a913

File tree

3 files changed

+9
-0
lines changed

3 files changed

+9
-0
lines changed

bson/bsonrw/extjson_parser.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ func newExtJSONParser(r io.Reader, canonical bool) *extJSONParser {
8686
func (ejp *extJSONParser) peekType() (bsontype.Type, error) {
8787
var t bsontype.Type
8888
var err error
89+
initialState := ejp.s
8990

9091
ejp.advanceState()
9192
switch ejp.s {
@@ -113,6 +114,9 @@ func (ejp *extJSONParser) peekType() (bsontype.Type, error) {
113114
case jpsInvalidState:
114115
err = ejp.err
115116
case jpsSawKey:
117+
if initialState == jpsStartState {
118+
return bsontype.EmbeddedDocument, nil
119+
}
116120
t = wrapperKeyBSONType(ejp.k)
117121

118122
switch t {

bson/bsonrw/extjson_parser_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,10 @@ func TestExtJSONParserPeekType(t *testing.T) {
155155
for _, tc := range cases {
156156
t.Run(tc.desc, func(t *testing.T) {
157157
ejp := newExtJSONParser(strings.NewReader(tc.input), true)
158+
// Manually set the parser's starting state to jpsSawColon so peekType will read ahead to find the extjson
159+
// type of the value. If not set, the parser will be in jpsStartState and advance to jpsSawKey, which will
160+
// cause it to return without peeking the extjson type.
161+
ejp.s = jpsSawColon
158162

159163
for i, eTyp := range tc.typs {
160164
errF := tc.errFs[i]

bson/extjson_prose_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ func TestExtJSON(t *testing.T) {
2727
{"timestamp - negative int32 value", `{"":{"$timestamp":{"t":0,"i":-1}}}`, false, timestampNegativeInt32Err},
2828
{"timestamp - negative int64 value", `{"":{"$timestamp":{"t":0,"i":-2147483649}}}`, false, timestampNegativeInt64Err},
2929
{"timestamp - value overflows uint32", `{"":{"$timestamp":{"t":0,"i":4294967296}}}`, false, timestampLargeValueErr},
30+
{"top level key is not treated as special", `{"$code": "foo"}`, false, nil},
3031
}
3132
for _, tc := range testCases {
3233
t.Run(tc.name, func(t *testing.T) {

0 commit comments

Comments
 (0)