From 3566fd62b8ee05d3bb82553d1beee31ab3391cdf Mon Sep 17 00:00:00 2001 From: crapStone Date: Mon, 29 Apr 2024 23:05:24 +0200 Subject: [PATCH] remove domain from cache when scheduled for renewal --- server/certificates/certificates.go | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/server/certificates/certificates.go b/server/certificates/certificates.go index f48d1b7..cf11078 100644 --- a/server/certificates/certificates.go +++ b/server/certificates/certificates.go @@ -10,12 +10,11 @@ import ( "strings" "time" - lru "github.com/hashicorp/golang-lru/v2" - "github.com/go-acme/lego/v4/certcrypto" "github.com/go-acme/lego/v4/certificate" "github.com/go-acme/lego/v4/challenge/tlsalpn01" "github.com/go-acme/lego/v4/lego" + lru "github.com/hashicorp/golang-lru/v2" "github.com/reugn/equalizer" "github.com/rs/zerolog/log" @@ -113,8 +112,13 @@ func TLSConfig(mainDomainSuffix string, } if tlsCertificate, ok := keyCache.Get(domain); ok { - // we can use an existing certificate object - return &tlsCertificate, nil + if shouldRenewCert(&tlsCertificate, 7) { + // if cert is up for renewal remove it from the cache + keyCache.Remove(domain) + } else { + // we can use an existing certificate object + return &tlsCertificate, nil + } } var tlsCertificate *tls.Certificate @@ -197,7 +201,7 @@ func (c *AcmeClient) retrieveCertFromDB(sni, mainDomainSuffix string, useDnsProv } // renew certificates 7 days before they expire - if tlsCertificate.Leaf.NotAfter.Before(time.Now().Add(7 * 24 * time.Hour)) { + if shouldRenewCert(&tlsCertificate, 7) { // TODO: use ValidTill of custom cert struct if res.CSR != nil && len(res.CSR) > 0 { // CSR stores the time when the renewal shall be tried again @@ -339,6 +343,11 @@ func SetupMainDomainCertificates(mainDomainSuffix string, acmeClient *AcmeClient return nil } +// shouldRenewCert returns true if the validity date of the cert is less than the given number of days in the future +func shouldRenewCert(cert *tls.Certificate, days uint) bool { + return cert.Leaf.NotAfter.Before(time.Now().Add(time.Duration(days) * 24 * time.Hour)) +} + func MaintainCertDB(ctx context.Context, interval time.Duration, acmeClient *AcmeClient, mainDomainSuffix string, certDB database.CertDB) { for { // delete expired certs that will be invalid until next clean up