lib/syncthing: Clean up / refactor LoadOrGenerateCertificate() utility function. (#8025)

LoadOrGenerateCertificate() takes two file path arguments, but then
uses the locations package to determine the actual path.  Fix that
with a minimally invasive change, by using the arguments instead.
Factor out GenerateCertificate().

The only caller of this function is cmd/syncthing, which passes the
same values, so this is technically a no-op.

* lib/tlsutil: Make storing generated certificate optional.  Avoid
  temporary cert and key files in tests, keep cert in memory.
This commit is contained in:
André Colomb
2021-11-07 23:59:48 +01:00
committed by GitHub
parent db15e52743
commit ec8a748514
7 changed files with 50 additions and 78 deletions
+1 -8
View File
@@ -9,7 +9,6 @@ package syncthing
import (
"io/ioutil"
"os"
"path/filepath"
"testing"
"time"
@@ -57,13 +56,7 @@ func TestShortIDCheck(t *testing.T) {
}
func TestStartupFail(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "syncthing-TestStartupFail-")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
cert, err := tlsutil.NewCertificate(filepath.Join(tmpDir, "cert"), filepath.Join(tmpDir, "key"), "syncthing", 365)
cert, err := tlsutil.NewCertificateInMemory("syncthing", 365)
if err != nil {
t.Fatal(err)
}
+7 -11
View File
@@ -25,22 +25,18 @@ import (
)
func LoadOrGenerateCertificate(certFile, keyFile string) (tls.Certificate, error) {
cert, err := tls.LoadX509KeyPair(
locations.Get(locations.CertFile),
locations.Get(locations.KeyFile),
)
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
l.Infof("Generating ECDSA key and certificate for %s...", tlsDefaultCommonName)
return tlsutil.NewCertificate(
locations.Get(locations.CertFile),
locations.Get(locations.KeyFile),
tlsDefaultCommonName,
deviceCertLifetimeDays,
)
return GenerateCertificate(certFile, keyFile)
}
return cert, nil
}
func GenerateCertificate(certFile, keyFile string) (tls.Certificate, error) {
l.Infof("Generating ECDSA key and certificate for %s...", tlsDefaultCommonName)
return tlsutil.NewCertificate(certFile, keyFile, tlsDefaultCommonName, deviceCertLifetimeDays)
}
func DefaultConfig(path string, myID protocol.DeviceID, evLogger events.Logger, noDefaultFolder bool) (config.Wrapper, error) {
newCfg, err := config.NewWithFreePorts(myID)
if err != nil {