From 6b626bcad37f8df07abc6e60e0546a85fd165eb4 Mon Sep 17 00:00:00 2001 From: Egon Elbre Date: Thu, 29 Feb 2024 15:41:43 +0200 Subject: [PATCH] private/date: fix PeriodToTime for invalid periods Updates https://github.com/storj/storj/issues/6818 Change-Id: I626945636bac901700b900a5594473fa33c3f288 --- private/date/utils.go | 10 ++++++++-- private/date/utils_test.go | 15 +++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/private/date/utils.go b/private/date/utils.go index ecbc53daa54d..5e2bdd605c7a 100644 --- a/private/date/utils.go +++ b/private/date/utils.go @@ -4,7 +4,10 @@ // Package date contains various date-related utilities package date -import "time" +import ( + "fmt" + "time" +) // MonthBoundary extract month from the provided date and returns its edges. func MonthBoundary(t time.Time) (time.Time, time.Time) { @@ -21,8 +24,11 @@ func DayBoundary(t time.Time) (time.Time, time.Time) { // PeriodToTime returns time.Time period in format YYYY-MM from string. func PeriodToTime(period string) (_ time.Time, err error) { + if len(period) < 7 { + return time.Time{}, fmt.Errorf("invalid period %q", period) + } + shortPeriod := period[:7] layout := "2006-01" - shortPeriod := period[0:7] result, err := time.Parse(layout, shortPeriod) if err != nil { return time.Time{}, err diff --git a/private/date/utils_test.go b/private/date/utils_test.go index bf7415d1ca81..6043af6d5ac7 100644 --- a/private/date/utils_test.go +++ b/private/date/utils_test.go @@ -48,6 +48,21 @@ func TestPeriodToTime(t *testing.T) { } } +func TestPeriodToTime_Invalid(t *testing.T) { + testCases := [...]struct { + period string + error string + }{ + {"", "invalid period \"\""}, + {"2020", "invalid period \"2020\""}, + } + + for _, tc := range testCases { + _, err := date.PeriodToTime(tc.period) + require.ErrorContains(t, err, tc.error) + } +} + func TestMonthsBetweenDates(t *testing.T) { testCases := [...]struct { from time.Time