Repository: fxamacker/cbor
Pull request #355 (2022-07-02 00:37:08)

Allow MaxNestedLevels to be up to 65535
### Description

This is a preemptive pr that solves #354. Namely, it increases MaxNestedLevels and adds a test for a deeply nested object. It's not a particularly hard thing to solve, but I wanted to be helpful. Let me know if you would like to pick a different maximum for MaxNestedLevels, or make any other changes.

#### PR Was Proposed and Welcomed in Currently Open Issue

- [] This PR was proposed and welcomed by maintainer(s) in issue #354
- [x] Closes or Updates Issue #354 

#### Checklist (for code PR only, ignore for docs PR)

- [x] Include unit tests that cover the new code
- [x] Pass all unit tests 
- [ ] Pass all 18 ci linters (golint, gosec, staticcheck, etc.)
- [x] Sign each commit with your real name and email.  
      Last line of each commit message should be in this format:  
      Signed-off-by: Firstname Lastname <firstname.lastname@example.com>
- [x] Certify the Developer's Certificate of Origin 1.1
      (see next section).

#### Certify the Developer's Certificate of Origin 1.1

- [x] By marking this item as completed, I certify 
      the Developer Certificate of Origin 1.1.

```
Developer Certificate of Origin
Version 1.1

Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
660 York Street, Suite 102,
San Francisco, CA 94110 USA

Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.

Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

(b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

(c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

(d) I understand and agree that this project and the contribution
    are public and that a record of the contribution (including all
    personal information I submit with it, including my sign-off) is
    maintained indefinitely and may be redistributed consistent with
    this project or the open source license(s) involved.
```



fxamacker: Added issue #354 to milestone 2.5.0.

Patch:
diff --git a/README.md b/README.md
index 9a11219..8b4b2c7 100644
--- a/README.md
+++ b/README.md
@@ -362,7 +362,7 @@ See [Options](#options) section for details about each setting.
 | IndefLength | **IndefLengthAllowed**, IndefLengthForbidden |
 | TagsMd | **TagsAllowed**, TagsForbidden |
 | ExtraReturnErrors | **ExtraDecErrorNone**, ExtraDecErrorUnknownField |
-| MaxNestedLevels | **32**, can be set to [4, 256] |
+| MaxNestedLevels | **32**, can be set to [4, 65535] |
 | MaxArrayElements | **131072**, can be set to [16, 2147483647] |
 | MaxMapPairs | **131072**, can be set to [16, 2147483647] |
 
@@ -697,7 +697,7 @@ If `IntDecConvertedSigned` is used and value overflows int64, UnmarshalTypeError
 
 | DecOptions.MaxNestedLevels | Description |
 | -------------------------- | ----------- |
-| 32 (default) | allowed setting is [4, 256] |
+| 32 (default) | allowed setting is [4, 65535] |
 
 <br>
 
diff --git a/decode.go b/decode.go
index 79ccaf8..f7ec882 100644
--- a/decode.go
+++ b/decode.go
@@ -287,7 +287,8 @@ type DecOptions struct {
 	TimeTag DecTagMode
 
 	// MaxNestedLevels specifies the max nested levels allowed for any combination of CBOR array, maps, and tags.
-	// Default is 32 levels and it can be set to [4, 256].
+	// Default is 32 levels and it can be set to [4, 65535]. Note that higher maximum levels of nesting can
+	// require larger amounts of stack to deserialize. Don't increase this higher than you require.
 	MaxNestedLevels int
 
 	// MaxArrayElements specifies the max number of elements for CBOR arrays.
@@ -402,8 +403,8 @@ func (opts DecOptions) decMode() (*decMode, error) {
 	}
 	if opts.MaxNestedLevels == 0 {
 		opts.MaxNestedLevels = 32
-	} else if opts.MaxNestedLevels < 4 || opts.MaxNestedLevels > 256 {
-		return nil, errors.New("cbor: invalid MaxNestedLevels " + strconv.Itoa(opts.MaxNestedLevels) + " (range is [4, 256])")
+	} else if opts.MaxNestedLevels < 4 || opts.MaxNestedLevels > 65535 {
+		return nil, errors.New("cbor: invalid MaxNestedLevels " + strconv.Itoa(opts.MaxNestedLevels) + " (range is [4, 65535])")
 	}
 	if opts.MaxArrayElements == 0 {
 		opts.MaxArrayElements = defaultMaxArrayElements


Test patch:
diff --git a/decode_test.go b/decode_test.go
index dc7ee13..3c1725e 100644
--- a/decode_test.go
+++ b/decode_test.go
@@ -3131,6 +3131,44 @@ func TestUnmarshalIntoMapError(t *testing.T) {
 	}
 }
 
+func TestUnmarshalDeepNesting(t *testing.T) {
+	// Construct this object rather than embed such a large constant in the code
+	type TestNode struct {
+		Value int
+		Child *TestNode
+	}
+	n := &TestNode{Value: 0}
+	root := n
+	for i := 0; i < 65534; i++ {
+		child := &TestNode{Value: i}
+		n.Child = child
+		n = child
+	}
+	em, err := EncOptions{}.EncMode()
+	if err != nil {
+		t.Errorf("EncMode() returned error %v", err)
+	}
+	cborData, err := em.Marshal(root)
+	if err != nil {
+		t.Errorf("Marshal() deeply nested object returned error %v", err)
+	}
+
+	// Try unmarshal it
+	dm, err := DecOptions{MaxNestedLevels: 65535}.DecMode()
+	if err != nil {
+		t.Errorf("DecMode() returned error %v", err)
+	}
+	var readback TestNode
+	err = dm.Unmarshal(cborData, &readback)
+	if err != nil {
+		t.Errorf("Unmarshal() of deeply nested object returned error: %v", err)
+	}
+	if !reflect.DeepEqual(root, &readback) {
+		t.Errorf("Unmarshal() of deeply nested object did not match\nGot: %#v\n Want: %#v\n",
+			&readback, root)
+	}
+}
+
 func TestStructToArrayError(t *testing.T) {
 	type coseHeader struct {
 		Alg int    `cbor:"1,keyasint,omitempty"`
@@ -3291,12 +3329,12 @@ func TestDecModeInvalidMaxNestedLevel(t *testing.T) {
 		{
 			name:         "MaxNestedLevels < 4",
 			opts:         DecOptions{MaxNestedLevels: 1},
-			wantErrorMsg: "cbor: invalid MaxNestedLevels 1 (range is [4, 256])",
+			wantErrorMsg: "cbor: invalid MaxNestedLevels 1 (range is [4, 65535])",
 		},
 		{
-			name:         "MaxNestedLevels > 256",
-			opts:         DecOptions{MaxNestedLevels: 257},
-			wantErrorMsg: "cbor: invalid MaxNestedLevels 257 (range is [4, 256])",
+			name:         "MaxNestedLevels > 65535",
+			opts:         DecOptions{MaxNestedLevels: 65536},
+			wantErrorMsg: "cbor: invalid MaxNestedLevels 65536 (range is [4, 65535])",
 		},
 	}
 	for _, tc := range testCases {