Skip to content

Commit

Permalink
go/common/cbor: Add UnmarshalTrusted for trusted inputs
Browse files Browse the repository at this point in the history
The new method relaxes some decoding restrictions for cases where the inputs are
trusted (e.g., because they are known to be generated by the local node itself).
  • Loading branch information
kostko committed Apr 1, 2020
1 parent 0396c4c commit 1e3ffef
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
4 changes: 4 additions & 0 deletions .changelog/2800.internal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
go/common/cbor: Add UnmarshalTrusted for trusted inputs

The new method relaxes some decoding restrictions for cases where the inputs are
trusted (e.g., because they are known to be generated by the local node itself).
27 changes: 25 additions & 2 deletions go/common/cbor/cbor.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,23 @@ var (
TagsMd: cbor.TagsForbidden,
}

// decOptions are decoding options for UNTRUSTED inputs (used by default).
decOptions = cbor.DecOptions{
DupMapKey: cbor.DupMapKeyEnforcedAPF,
IndefLength: cbor.IndefLengthForbidden,
TagsMd: cbor.TagsForbidden,
}

encMode cbor.EncMode
decMode cbor.DecMode
// decOptionsTrusted are decoding options for TRUSTED inputs. They are only used when explicitly
// requested by using the UnmarshalTrusted method.
decOptionsTrusted = cbor.DecOptions{
MaxArrayElements: 134217728, // Maximum allowed.
MaxMapPairs: 134217728, // Maximum allowed.
}

encMode cbor.EncMode
decMode cbor.DecMode
decModeTrusted cbor.DecMode
)

func init() {
Expand All @@ -45,6 +54,9 @@ func init() {
if decMode, err = decOptions.DecMode(); err != nil {
panic(err)
}
if decModeTrusted, err = decOptionsTrusted.DecMode(); err != nil {
panic(err)
}
}

// FixSliceForSerde will convert `nil` to `[]byte` to work around serde
Expand Down Expand Up @@ -74,6 +86,17 @@ func Unmarshal(data []byte, dst interface{}) error {
return decMode.Unmarshal(data, dst)
}

// UnmarshalTrusted deserializes a CBOR byte vector into a given type.
//
// This method MUST ONLY BE USED FOR TRUSTED INPUTS as it relaxes some decoding restrictions.
func UnmarshalTrusted(data []byte, dst interface{}) error {
if data == nil {
return nil
}

return decModeTrusted.Unmarshal(data, dst)
}

// MustUnmarshal deserializes a CBOR byte vector into a given type.
// Panics if unmarshal fails.
func MustUnmarshal(data []byte, dst interface{}) {
Expand Down

0 comments on commit 1e3ffef

Please sign in to comment.