From 30093737ccaf73dba85f3d5fb6ec0d7b2b6b4550 Mon Sep 17 00:00:00 2001 From: Kim Shrier Date: Sat, 16 Nov 2024 02:41:16 -0700 Subject: [PATCH] x.encoding.asn1: fix time creation to also accommodate negative timezone offsets (#22861) --- vlib/x/encoding/asn1/time.v | 4 ++-- vlib/x/encoding/asn1/time_test.v | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/vlib/x/encoding/asn1/time.v b/vlib/x/encoding/asn1/time.v index 247790f599b90c..a728a1f39b32ce 100644 --- a/vlib/x/encoding/asn1/time.v +++ b/vlib/x/encoding/asn1/time.v @@ -56,7 +56,7 @@ fn UtcTime.from_time(t time.Time) !UtcTime { s := utime.custom_format(default_utctime_format) // 20241113060446+0 // Its rather a hack, not efieient as should be. // TODO: make it better - str := s.split('+') + str := s.split_any('+-') val := str[0] + 'Z' utc := UtcTime.new(val)! return utc @@ -231,7 +231,7 @@ pub fn GeneralizedTime.from_time(t time.Time) !GeneralizedTime { u := t.local_to_utc() s := u.custom_format(default_genztime_format) // adds support directly from time.Time - src := s.split('+') + src := s.split_any('+-') val := src[0] + 'Z' gt := GeneralizedTime.new(val)! diff --git a/vlib/x/encoding/asn1/time_test.v b/vlib/x/encoding/asn1/time_test.v index 5e6b04f23056b5..b0637e8429590a 100644 --- a/vlib/x/encoding/asn1/time_test.v +++ b/vlib/x/encoding/asn1/time_test.v @@ -3,6 +3,7 @@ // that can be found in the LICENSE file. module asn1 +import os import time fn test_serialize_utctime_basic() ! { @@ -42,6 +43,18 @@ fn test_create_utctime_from_std_time() ! { assert tinp_back.value == inp } +fn test_create_utctime_from_std_time_with_negative_offset() ! { + tz := os.getenv('TZ') + os.setenv('TZ', 'utc 1', true) + + defer { + os.setenv('TZ', tz, true) + } + + now := time.new(year: 2024, month: 11, day: 13, hour: 17, minute: 45, second: 50) + UtcTime.from_time(now)! +} + fn test_serialize_utctime_error_without_z() ! { // this input does not contains zulu 'Z' part inp := '191215190210' @@ -115,3 +128,15 @@ fn test_create_generalizedtime_from_std_time() ! { assert g_utc_back.value == s } + +fn test_create_generalizedtime_from_std_time_with_negative_offset() ! { + tz := os.getenv('TZ') + os.setenv('TZ', 'utc 1', true) + + defer { + os.setenv('TZ', tz, true) + } + + now := time.new(year: 2024, month: 11, day: 13, hour: 17, minute: 45, second: 50) + GeneralizedTime.from_time(now)! +}