Repository: fxamacker/cbor
Pull request #506 (2024-03-16 21:53:07)

Add decoding option to specific how to decode tag 0 or 1 into any
Adds a decoding option to specify how to decode CBOR tag 0 or 1 data item into an empty interface. 
Based on the specified mode, Unmarshal can return a time.Time value or a time string in a specific format.

<!--
Thank you for your interest in contributing to fxamacker/cbor!
-->

### Description


<!-- 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 #496
- [x] Closes or Updates Issue #496 

#### 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.
```



fxamacker: @ssuriyan7 Thanks for opening this PR!  I'll try to take a look this week/weekend.  :pray: 

Patch:
diff --git a/.github/workflows/ci-go-cover.yml b/.github/workflows/ci-go-cover.yml
index efe01fd..99b977c 100644
--- a/.github/workflows/ci-go-cover.yml
+++ b/.github/workflows/ci-go-cover.yml
@@ -36,7 +36,7 @@ jobs:
     runs-on: ubuntu-latest
     steps:
     - name: Checkout code
-      uses: actions/checkout@9bb56186c3b09b4f86b1c65136769dd318469633 # v4.1.2
+      uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
     - name: Install Go
       uses: actions/setup-go@93397bea11091df50f3d7e59dc26a7711a8bcfbe # v4.1.0
       with:
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 622b0c8..5bbd23f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -35,7 +35,7 @@ jobs:
         check-latest: true
         
     - name: Checkout code
-      uses: actions/checkout@9bb56186c3b09b4f86b1c65136769dd318469633 # v4.1.2
+      uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
       with:
         fetch-depth: 1
 
diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
index ca2ac33..e80b131 100644
--- a/.github/workflows/codeql-analysis.yml
+++ b/.github/workflows/codeql-analysis.yml
@@ -28,18 +28,18 @@ jobs:
 
     steps:
     - name: Checkout repository
-      uses: actions/checkout@9bb56186c3b09b4f86b1c65136769dd318469633 # v4.1.2
+      uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
 
     # Initializes the CodeQL tools for scanning.
     - name: Initialize CodeQL
-      uses: github/codeql-action/init@1b1aada464948af03b950897e5eb522f92603cc2 # v3.24.9
+      uses: github/codeql-action/init@8a470fddafa5cbb6266ee11b37ef4d8aae19c571 # v3.24.6
       with:
         languages: ${{ matrix.language }}
 
     # Autobuild attempts to build any compiled languages  (C/C++, C#, or Java).
     # If this step fails, then you should remove it and run the build manually (see below)
     - name: Autobuild
-      uses: github/codeql-action/autobuild@1b1aada464948af03b950897e5eb522f92603cc2 # v3.24.9
+      uses: github/codeql-action/autobuild@8a470fddafa5cbb6266ee11b37ef4d8aae19c571 # v3.24.6
 
     - name: Perform CodeQL Analysis
-      uses: github/codeql-action/analyze@1b1aada464948af03b950897e5eb522f92603cc2 # v3.24.9
+      uses: github/codeql-action/analyze@8a470fddafa5cbb6266ee11b37ef4d8aae19c571 # v3.24.6
diff --git a/.github/workflows/govulncheck.yml b/.github/workflows/govulncheck.yml
index 9036c53..885a13a 100644
--- a/.github/workflows/govulncheck.yml
+++ b/.github/workflows/govulncheck.yml
@@ -33,7 +33,7 @@ jobs:
       contents: read
     steps:
     - name: Checkout source
-      uses: actions/checkout@9bb56186c3b09b4f86b1c65136769dd318469633 # v4.1.2
+      uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
       with:
         fetch-depth: 1
     - name: Set up Go
diff --git a/.github/workflows/safer-golangci-lint.yml b/.github/workflows/safer-golangci-lint.yml
index 475870f..cf198bf 100644
--- a/.github/workflows/safer-golangci-lint.yml
+++ b/.github/workflows/safer-golangci-lint.yml
@@ -32,7 +32,7 @@ jobs:
       contents: read
     steps:
       - name: Checkout source
-        uses: actions/checkout@9bb56186c3b09b4f86b1c65136769dd318469633 # v4.1.2
+        uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
         with:
           fetch-depth: 1
 
diff --git a/decode.go b/decode.go
index c2b5e00..0c8b398 100644
--- a/decode.go
+++ b/decode.go
@@ -472,6 +472,30 @@ func (uttam UnrecognizedTagToAnyMode) valid() bool {
 	return uttam >= 0 && uttam < maxUnrecognizedTagToAny
 }
 
+// TimeTagToAnyMode specifies how to decode CBOR tag 0 and 1 into an empty interface (any).
+// Based on the specified mode, Unmarshal can return a time.Time value or a time string in a specific format.
+type TimeTagToAnyMode int
+
+const (
+	// TimeTagToTime decodes CBOR tag 0 and 1 into a time.Time value
+	// when decoding tag 0 or 1 into an empty interface.
+	TimeTagToTime TimeTagToAnyMode = iota
+
+	// TimeTagToRFC3339 decodes CBOR tag 0 and 1 into a time string in RFC3339 format
+	// when decoding tag 0 or 1 into an empty interface.
+	TimeTagToRFC3339
+
+	// TimeTagToRFC3339Nano decodes CBOR tag 0 and 1 into a time string in RFC3339Nano format
+	// when decoding tag 0 or 1 into an empty interface.
+	TimeTagToRFC3339Nano
+
+	maxTimeTagToAnyMode
+)
+
+func (tttam TimeTagToAnyMode) valid() bool {
+	return tttam >= 0 && tttam < maxTimeTagToAnyMode
+}
+
 // DecOptions specifies decoding options.
 type DecOptions struct {
 	// DupMapKey specifies whether to enforce duplicate map key.
@@ -564,6 +588,10 @@ type DecOptions struct {
 	// UnrecognizedTagToAny specifies how to decode unrecognized CBOR tag into an empty interface.
 	// Currently, recognized CBOR tag numbers are 0, 1, 2, 3, or registered by TagSet.
 	UnrecognizedTagToAny UnrecognizedTagToAnyMode
+
+	// TimeTagToAnyMode specifies how to decode CBOR tag 0 and 1 into an empty interface (any).
+	// Based on the specified mode, Unmarshal can return a time.Time value or a time string in a specific format.
+	TimeTagToAny TimeTagToAnyMode
 }
 
 // DecMode returns DecMode with immutable options and no tags (safe for concurrency).
@@ -717,6 +745,10 @@ func (opts DecOptions) decMode() (*decMode, error) {
 		return nil, errors.New("cbor: invalid UnrecognizedTagToAnyMode " + strconv.Itoa(int(opts.UnrecognizedTagToAny)))
 	}
 
+	if !opts.TimeTagToAny.valid() {
+		return nil, errors.New("cbor: invalid TimeTagToAny " + strconv.Itoa(int(opts.TimeTagToAny)))
+	}
+
 	dm := decMode{
 		dupMapKey:             opts.DupMapKey,
 		timeTag:               opts.TimeTag,
@@ -736,6 +768,7 @@ func (opts DecOptions) decMode() (*decMode, error) {
 		byteStringToString:    opts.ByteStringToString,
 		fieldNameByteString:   opts.FieldNameByteString,
 		unrecognizedTagToAny:  opts.UnrecognizedTagToAny,
+		timeTagToAny:          opts.TimeTagToAny,
 	}
 
 	return &dm, nil
@@ -807,6 +840,7 @@ type decMode struct {
 	byteStringToString    ByteStringToStringMode
 	fieldNameByteString   FieldNameByteStringMode
 	unrecognizedTagToAny  UnrecognizedTagToAnyMode
+	timeTagToAny          TimeTagToAnyMode
 }
 
 var defaultDecMode, _ = DecOptions{}.decMode()
@@ -832,6 +866,7 @@ func (dm *decMode) DecOptions() DecOptions {
 		ByteStringToString:    dm.byteStringToString,
 		FieldNameByteString:   dm.fieldNameByteString,
 		UnrecognizedTagToAny:  dm.unrecognizedTagToAny,
+		TimeTagToAny:          dm.timeTagToAny,
 	}
 }
 
@@ -1503,7 +1538,25 @@ func (d *decoder) parse(skipSelfDescribedTag bool) (interface{}, error) { //noli
 		case 0, 1:
 			d.off = tagOff
 			tm, _, err := d.parseToTime()
-			return tm, err
+			if err != nil {
+				return nil, err
+			}
+			switch d.dm.timeTagToAny {
+			case TimeTagToTime:
+				return tm, nil
+			case TimeTagToRFC3339:
+				if tagNum == 1 {
+					tm = tm.UTC()
+				}
+				return tm.Format(time.RFC3339), nil
+			case TimeTagToRFC3339Nano:
+				if tagNum == 1 {
+					tm = tm.UTC()
+				}
+				return tm.Format(time.RFC3339Nano), nil
+			default:
+				// not reachable
+			}
 		case 2:
 			b, _ := d.parseByteString()
 			bi := new(big.Int).SetBytes(b)


Test patch:
diff --git a/decode_test.go b/decode_test.go
index 54da82f..9bc4c88 100644
--- a/decode_test.go
+++ b/decode_test.go
@@ -4912,6 +4912,7 @@ func TestDecOptions(t *testing.T) {
 		ByteStringToString:    ByteStringToStringAllowed,
 		FieldNameByteString:   FieldNameByteStringAllowed,
 		UnrecognizedTagToAny:  UnrecognizedTagContentToAny,
+		TimeTagToAny:          TimeTagToRFC3339,
 	}
 	ov := reflect.ValueOf(opts1)
 	for i := 0; i < ov.NumField(); i++ {
@@ -8658,3 +8659,92 @@ func TestUnmarshalWithUnrecognizedTagToAnyModeForSharedTag(t *testing.T) {
 func isCBORNil(data []byte) bool {
 	return len(data) > 0 && (data[0] == 0xf6 || data[0] == 0xf7)
 }
+
+func TestDecModeInvalidTimeTagToAnyMode(t *testing.T) {
+	for _, tc := range []struct {
+		name         string
+		opts         DecOptions
+		wantErrorMsg string
+	}{
+		{
+			name:         "below range of valid modes",
+			opts:         DecOptions{TimeTagToAny: -1},
+			wantErrorMsg: "cbor: invalid TimeTagToAny -1",
+		},
+		{
+			name:         "above range of valid modes",
+			opts:         DecOptions{TimeTagToAny: 4},
+			wantErrorMsg: "cbor: invalid TimeTagToAny 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 TestDecModeTimeTagToAny(t *testing.T) {
+	for _, tc := range []struct {
+		name string
+		opts DecOptions
+		in   []byte
+		want interface{}
+	}{
+		{
+			name: "Unmarshal tag 0 data to time.Time when TimeTagToAny is not set",
+			opts: DecOptions{},
+			in:   hexDecode("c074323031332d30332d32315432303a30343a30305a"),
+			want: time.Date(2013, 3, 21, 20, 4, 0, 0, time.UTC),
+		},
+		{
+			name: "Unmarshal tag 1 data to time.Time when TimeTagToAny is not set",
+			opts: DecOptions{},
+			in:   hexDecode("c11a514b67b0"),
+			want: time.Date(2013, 3, 21, 20, 4, 0, 0, time.UTC),
+		},
+		{
+			name: "Unmarshal tag 0 data to RFC3339 string when TimeTagToAny is set",
+			opts: DecOptions{TimeTagToAny: TimeTagToRFC3339},
+			in:   hexDecode("c074323031332d30332d32315432303a30343a30305a"),
+			want: "2013-03-21T20:04:00Z",
+		},
+		{
+			name: "Unmarshal tag 1 data to RFC3339 string when TimeTagToAny is set",
+			opts: DecOptions{TimeTagToAny: TimeTagToRFC3339},
+			in:   hexDecode("c11a514b67b0"),
+			want: "2013-03-21T20:04:00Z",
+		},
+		{
+			name: "Unmarshal tag 0 data to RFC3339Nano string when TimeTagToAny is set",
+			opts: DecOptions{TimeTagToAny: TimeTagToRFC3339Nano},
+			in:   hexDecode("c076323031332d30332d32315432303a30343a30302e355a"),
+			want: "2013-03-21T20:04:00.5Z",
+		},
+		{
+			name: "Unmarshal tag 1 data to RFC3339Nano string when TimeTagToAny is set",
+			opts: DecOptions{TimeTagToAny: TimeTagToRFC3339Nano},
+			in:   hexDecode("c1fb41d452d9ec200000"),
+			want: "2013-03-21T20:04:00.5Z",
+		},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			dm, err := tc.opts.DecMode()
+			if err != nil {
+				t.Fatal(err)
+			}
+
+			var got interface{}
+			if err := dm.Unmarshal(tc.in, &got); err != nil {
+				t.Errorf("unexpected error: %v", err)
+			}
+
+			compareNonFloats(t, tc.in, got, tc.want)
+
+		})
+	}
+}