Use hashicorp's LRU cache for DNS & certificates

DNS caching is also limited to 30 seconds now instead of 5 minutes
This commit is contained in:
Moritz Marquardt 2024-04-16 22:22:09 +02:00 committed by crapStone
parent eb08c46dcd
commit 7071ee9bff
8 changed files with 50 additions and 24 deletions

View file

@ -10,6 +10,8 @@ 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"
@ -26,12 +28,14 @@ import (
var ErrUserRateLimitExceeded = errors.New("rate limit exceeded: 10 certificates per user per 24 hours")
var keyCache *lru.Cache[string, tls.Certificate]
// TLSConfig returns the configuration for generating, serving and cleaning up Let's Encrypt certificates.
func TLSConfig(mainDomainSuffix string,
giteaClient *gitea.Client,
acmeClient *AcmeClient,
firstDefaultBranch string,
keyCache, challengeCache, dnsLookupCache, canonicalDomainCache cache.ICache,
challengeCache cache.ICache, canonicalDomainCache cache.ICache,
certDB database.CertDB,
noDNS01 bool,
rawDomain string,
@ -86,7 +90,7 @@ func TLSConfig(mainDomainSuffix string,
}
} else {
var targetRepo, targetBranch string
targetOwner, targetRepo, targetBranch = dnsutils.GetTargetFromDNS(domain, mainDomainSuffix, firstDefaultBranch, dnsLookupCache)
targetOwner, targetRepo, targetBranch = dnsutils.GetTargetFromDNS(domain, mainDomainSuffix, firstDefaultBranch)
if targetOwner == "" {
// DNS not set up, return main certificate to redirect to the docs
domain = mainDomainSuffix
@ -105,9 +109,17 @@ func TLSConfig(mainDomainSuffix string,
}
}
if keyCache == nil {
var err error
keyCache, err = lru.New[string, tls.Certificate](4096)
if err != nil {
panic(err) // This should only happen if 4096 < 0 at the time of writing, which should be reason enough to panic.
}
}
if tlsCertificate, ok := keyCache.Get(domain); ok {
// we can use an existing certificate object
return tlsCertificate.(*tls.Certificate), nil
return &tlsCertificate, nil
}
var tlsCertificate *tls.Certificate
@ -132,9 +144,7 @@ func TLSConfig(mainDomainSuffix string,
}
}
if err := keyCache.Set(domain, tlsCertificate, 15*time.Minute); err != nil {
return nil, err
}
keyCache.Add(domain, *tlsCertificate)
return tlsCertificate, nil
},
NextProtos: []string{