Repository: fxamacker/cbor
Pull request #524 (2024-04-24 17:20:16)

Add a decoding option to allow decoding byte string into time.Time.
<!--
Thank you for your interest in contributing to fxamacker/cbor!
-->

### Description

This is a continuation of the work begun (and nearly completed) by @ssuriyan7 in https://github.com/fxamacker/cbor/pull/517.

<!-- For code contributions, please complete all the items below this line. -->
<!-- For documentation-only contributions, please delete everything below this line. -->

#### PR Was Proposed and Welcomed in Currently Open Issue

- [x] This PR was proposed and welcomed by maintainer(s) in issue #497
- [x] Closes or Updates Issue #497

#### Checklist (for code PR only, ignore for docs PR)

- [x] Include unit tests that cover the new code
- [x] Pass all unit tests 
- [x] Pass all lint checks in CI (goimports, 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.
```




Patch:
diff --git a/decode.go b/decode.go
index 6465191..c326998 100644
--- a/decode.go
+++ b/decode.go
@@ -576,6 +576,23 @@ func (idm InfMode) valid() bool {
 	return idm >= 0 && idm < maxInfDecode
 }
 
+// ByteStringToTimeMode specifies the behavior when decoding a CBOR byte string into a Go time.Time.
+type ByteStringToTimeMode int
+
+const (
+	// ByteStringToTimeForbidden generates an error on an attempt to decode a CBOR byte string into a Go time.Time.
+	ByteStringToTimeForbidden ByteStringToTimeMode = iota
+
+	// ByteStringToTimeAllowed permits decoding a CBOR byte string into a Go time.Time.
+	ByteStringToTimeAllowed
+
+	maxByteStringToTimeMode
+)
+
+func (bttm ByteStringToTimeMode) valid() bool {
+	return bttm >= 0 && bttm < maxByteStringToTimeMode
+}
+
 // DecOptions specifies decoding options.
 type DecOptions struct {
 	// DupMapKey specifies whether to enforce duplicate map key.
@@ -690,6 +707,9 @@ type DecOptions struct {
 	// Inf specifies how to decode floating-point values (major type 7, additional information
 	// 25 through 27) representing positive or negative infinity.
 	Inf InfMode
+
+	// ByteStringToTimeMode specifies the behavior when decoding a CBOR byte string into a Go time.Time.
+	ByteStringToTime ByteStringToTimeMode
 }
 
 // DecMode returns DecMode with immutable options and no tags (safe for concurrency).
@@ -868,6 +888,10 @@ func (opts DecOptions) decMode() (*decMode, error) {
 		return nil, errors.New("cbor: invalid InfDec " + strconv.Itoa(int(opts.Inf)))
 	}
 
+	if !opts.ByteStringToTime.valid() {
+		return nil, errors.New("cbor: invalid ByteStringToTime " + strconv.Itoa(int(opts.ByteStringToTime)))
+	}
+
 	dm := decMode{
 		dupMapKey:             opts.DupMapKey,
 		timeTag:               opts.TimeTag,
@@ -891,6 +915,7 @@ func (opts DecOptions) decMode() (*decMode, error) {
 		simpleValues:          simpleValues,
 		nanDec:                opts.NaN,
 		infDec:                opts.Inf,
+		byteStringToTime:      opts.ByteStringToTime,
 	}
 
 	return &dm, nil
@@ -966,6 +991,7 @@ type decMode struct {
 	simpleValues          *SimpleValueRegistry
 	nanDec                NaNMode
 	infDec                InfMode
+	byteStringToTime      ByteStringToTimeMode
 }
 
 var defaultDecMode, _ = DecOptions{}.decMode()
@@ -1002,6 +1028,7 @@ func (dm *decMode) DecOptions() DecOptions {
 		SimpleValues:          simpleValues,
 		NaN:                   dm.nanDec,
 		Inf:                   dm.infDec,
+		ByteStringToTime:      dm.byteStringToTime,
 	}
 }
 
@@ -1470,6 +1497,16 @@ func (d *decoder) parseToTime() (time.Time, bool, error) {
 	}
 
 	switch t := d.nextCBORType(); t {
+	case cborTypeByteString:
+		if d.dm.byteStringToTime == ByteStringToTimeAllowed {
+			b, _ := d.parseByteString()
+			t, err := time.Parse(time.RFC3339, string(b))
+			if err != nil {
+				return time.Time{}, false, fmt.Errorf("cbor: cannot set %q for time.Time: %w", string(b), err)
+			}
+			return t, true, nil
+		}
+		return time.Time{}, false, &UnmarshalTypeError{CBORType: t.String(), GoType: typeTime.String()}
 	case cborTypeTextString:
 		s, err := d.parseTextString()
 		if err != nil {


Test patch:
diff --git a/decode_test.go b/decode_test.go
index 89e47d1..54f4b07 100644
--- a/decode_test.go
+++ b/decode_test.go
@@ -4921,6 +4921,7 @@ func TestDecOptions(t *testing.T) {
 		SimpleValues:          simpleValues,
 		NaN:                   NaNDecodeForbidden,
 		Inf:                   InfDecodeForbidden,
+		ByteStringToTime:      ByteStringToTimeAllowed,
 	}
 	ov := reflect.ValueOf(opts1)
 	for i := 0; i < ov.NumField(); i++ {
@@ -9426,3 +9427,88 @@ func TestInfDecMode(t *testing.T) {
 		})
 	}
 }
+
+func TestDecModeInvalidByteStringToTimeMode(t *testing.T) {
+	for _, tc := range []struct {
+		name         string
+		opts         DecOptions
+		wantErrorMsg string
+	}{
+		{
+			name:         "below range of valid modes",
+			opts:         DecOptions{ByteStringToTime: -1},
+			wantErrorMsg: "cbor: invalid ByteStringToTime -1",
+		},
+		{
+			name:         "above range of valid modes",
+			opts:         DecOptions{ByteStringToTime: 4},
+			wantErrorMsg: "cbor: invalid ByteStringToTime 4",
+		},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			_, err := tc.opts.DecMode()
+			if err == nil {
+				t.Errorf("Expected non nil error from DecMode()")
+			} else if err.Error() != tc.wantErrorMsg {
+				t.Errorf("Expected error: %q, want: %q \n", tc.wantErrorMsg, err.Error())
+			}
+		})
+	}
+}
+
+func TestDecModeByteStringToTime(t *testing.T) {
+	for _, tc := range []struct {
+		name         string
+		opts         DecOptions
+		in           []byte
+		want         time.Time
+		wantErrorMsg string
+	}{
+		{
+			name:         "Unmarshal byte string to time.Time when ByteStringToTime is not set",
+			opts:         DecOptions{},
+			in:           hexDecode("54323031332D30332D32315432303A30343A30305A"), // '2013-03-21T20:04:00Z'
+			wantErrorMsg: "cbor: cannot unmarshal byte string into Go value of type time.Time",
+		},
+		{
+			name: "Unmarshal byte string to time.Time when ByteStringToTime is set to ByteStringToTimeAllowed",
+			opts: DecOptions{ByteStringToTime: ByteStringToTimeAllowed},
+			in:   hexDecode("54323031332D30332D32315432303A30343A30305A"), // '2013-03-21T20:04:00Z'
+			want: time.Date(2013, 3, 21, 20, 4, 0, 0, time.UTC),
+		},
+		{
+			name: "Unmarshal byte string to time.Time with nano when ByteStringToTime is set to ByteStringToTimeAllowed",
+			opts: DecOptions{ByteStringToTime: ByteStringToTimeAllowed},
+			in:   hexDecode("56323031332D30332D32315432303A30343A30302E355A"), // '2013-03-21T20:04:00.5Z'
+			want: time.Date(2013, 3, 21, 20, 4, 0, 500000000, time.UTC),
+		},
+		{
+			name:         "Unmarshal a byte string that is not a valid RFC3339 timestamp to time.Time when ByteStringToTime is set to ByteStringToTimeAllowed",
+			opts:         DecOptions{ByteStringToTime: ByteStringToTimeAllowed},
+			in:           hexDecode("4B696E76616C696454657874"), // 'invalidText'
+			wantErrorMsg: `cbor: cannot set "invalidText" for time.Time: parsing time "invalidText" as "2006-01-02T15:04:05Z07:00": cannot parse "invalidText" as "2006"`,
+		},
+		{
+			name:         "Unmarshal a byte string that is not a valid utf8 sequence to time.Time when ByteStringToTime is set to ByteStringToTimeAllowed",
+			opts:         DecOptions{ByteStringToTime: ByteStringToTimeAllowed},
+			in:           hexDecode("54323031338030332D32315432303A30343A30305A"), // "2013\x8003-21T20:04:00Z" -- the first hyphen of a valid RFC3339 string is replaced by a continuation byte
+			wantErrorMsg: `cbor: cannot set "2013\x8003-21T20:04:00Z" for time.Time: parsing time "2013\x8003-21T20:04:00Z" as "2006-01-02T15:04:05Z07:00": cannot parse "\x8003-21T20:04:00Z" as "-"`,
+		},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			dm, err := tc.opts.DecMode()
+			if err != nil {
+				t.Fatal(err)
+			}
+
+			var got time.Time
+			if err := dm.Unmarshal(tc.in, &got); err != nil {
+				if tc.wantErrorMsg != err.Error() {
+					t.Errorf("unexpected error: got %v want %v", err, tc.wantErrorMsg)
+				}
+			} else {
+				compareNonFloats(t, tc.in, got, tc.want)
+			}
+		})
+	}
+}