code.vegaprotocol.io/vega@v0.79.0/datanode/gateway/tlsconfig.go (about)

     1  // Copyright (C) 2023 Gobalsky Labs Limited
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU Affero General Public License as
     5  // published by the Free Software Foundation, either version 3 of the
     6  // License, or (at your option) any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU Affero General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU Affero General Public License
    14  // along with this program.  If not, see <http://www.gnu.org/licenses/>.
    15  
    16  package gateway
    17  
    18  import (
    19  	"crypto/tls"
    20  	"errors"
    21  	"net/http"
    22  
    23  	"code.vegaprotocol.io/vega/paths"
    24  
    25  	"golang.org/x/crypto/acme/autocert"
    26  )
    27  
    28  func GenerateTlsConfig(g *Config, vegaPaths paths.Paths) (*tls.Config, http.Handler, error) {
    29  	if g.HTTPSEnabled {
    30  		if g.AutoCertDomain != "" {
    31  			if g.CertificateFile != "" || g.KeyFile != "" {
    32  				return nil, nil, errors.New("autocert is enabled, and a pre-generated certificate/key specified; use one or the other")
    33  			}
    34  			certDir := vegaPaths.StatePathFor(paths.DataNodeAutoCertHome)
    35  
    36  			certManager := autocert.Manager{
    37  				Prompt:     autocert.AcceptTOS,
    38  				HostPolicy: autocert.HostWhitelist(g.AutoCertDomain),
    39  				Cache:      autocert.DirCache(certDir),
    40  			}
    41  
    42  			return &tls.Config{
    43  				GetCertificate: certManager.GetCertificate,
    44  				// NextProtos:     []string{"http/1.1", "acme-tls/1"},
    45  			}, certManager.HTTPHandler(nil), nil
    46  		}
    47  
    48  		certificate, err := tls.LoadX509KeyPair(g.CertificateFile, g.KeyFile)
    49  		if err != nil {
    50  			return nil, nil, err
    51  		}
    52  		certificates := []tls.Certificate{certificate}
    53  		return &tls.Config{
    54  			Certificates: certificates,
    55  		}, nil, nil
    56  	}
    57  
    58  	return nil, nil, nil
    59  }