From 2881f4a3c8b883af3d2cbbd3a3aeefadeb3d471e Mon Sep 17 00:00:00 2001 From: Adam Bernot Date: Fri, 10 Jul 2026 11:21:17 -0700 Subject: [PATCH] fix: avoid panic in ParseDuration on trailing whitespace Trim leading and trailing whitespace from the input duration string at the start of ParseDuration. This prevents a panic in the parsing loop when strings.TrimLeftFunc(s, unicode.IsSpace) trims a string consisting entirely of trailing spaces into an empty string, which subsequently causes an index out of bounds error when checking s[0]. Added regression test cases covering leading, trailing, and combined spaces around durations (e.g., " 1s ", "1s ", " 1s"). Signed-off-by: Adam Bernot --- duration.go | 1 + duration_test.go | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/duration.go b/duration.go index f2ab7ff..d9a970a 100644 --- a/duration.go +++ b/duration.go @@ -144,6 +144,7 @@ func (d *Duration) UnmarshalText(data []byte) error { // validation is performed func ParseDuration(s string) (time.Duration, error) { // NOTE: this code is largely inspired by the standard library. orig := s + s = strings.TrimSpace(s) var d uint64 neg := false diff --git a/duration_test.go b/duration_test.go index 5052ee9..9ab05f8 100644 --- a/duration_test.go +++ b/duration_test.go @@ -162,6 +162,11 @@ func TestDurationParser(t *testing.T) { "1 m45 s": time.Minute + 45*time.Second, "1m 45s": time.Minute + 45*time.Second, "1 minute 45 seconds": time.Minute + 45*time.Second, + + // leading and trailing spaces + " 1s ": 1 * time.Second, + "1s ": 1 * time.Second, + " 1s": 1 * time.Second, } for str, dur := range testcases {