From 19e9de3497bbf85396cc699c8ab381520531ec24 Mon Sep 17 00:00:00 2001 From: yongguangl <1363186473@qq.com> Date: Mon, 11 Jul 2022 23:53:55 +0800 Subject: [PATCH] fix: NotAfter is not set when ValidFor is set (#9911) Signed-off-by: yongguangl <1363186473@qq.com> --- util/tls/tls.go | 2 ++ util/tls/tls_test.go | 15 +++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/util/tls/tls.go b/util/tls/tls.go index f803099bfa08a..9712ecbd7b390 100644 --- a/util/tls/tls.go +++ b/util/tls/tls.go @@ -247,6 +247,8 @@ func generate(opts CertOptions) ([]byte, crypto.PrivateKey, error) { var validFor time.Duration if opts.ValidFor == 0 { validFor = 365 * 24 * time.Hour + } else { + validFor = opts.ValidFor } notAfter := notBefore.Add(validFor) diff --git a/util/tls/tls_test.go b/util/tls/tls_test.go index 02ac4319e320c..574c5d6efcb1b 100644 --- a/util/tls/tls_test.go +++ b/util/tls/tls_test.go @@ -252,6 +252,21 @@ func TestGenerate(t *testing.T) { assert.NotNil(t, cert) assert.GreaterOrEqual(t, (time.Now().Unix())+int64(1*time.Hour), cert.NotBefore.Unix()) }) + + for _, year := range []int{1, 2, 3, 10} { + t.Run(fmt.Sprintf("Create certificate with specified ValidFor %d year", year), func(t *testing.T) { + validFrom, validFor := time.Now(), 365*24*time.Hour*time.Duration(year) + opts := CertOptions{Hosts: []string{"localhost"}, Organization: "Acme", ValidFrom: validFrom, ValidFor: validFor} + certBytes, privKey, err := generate(opts) + assert.NoError(t, err) + assert.NotNil(t, privKey) + cert, err := x509.ParseCertificate(certBytes) + assert.NoError(t, err) + assert.NotNil(t, cert) + t.Logf("certificate expiration time %s", cert.NotAfter) + assert.Equal(t, validFrom.Unix()+int64(validFor.Seconds()), cert.NotAfter.Unix()) + }) + } } func TestGeneratePEM(t *testing.T) {