From 48c8606d4082e28dabd2d5ee7e2d9b752728153e Mon Sep 17 00:00:00 2001 From: David Choi Date: Thu, 22 Feb 2024 17:50:03 -0800 Subject: [PATCH] Add support for TLS files via config. --- service/endpoint/config.go | 2 ++ service/endpoint/service.go | 12 ++++++++++++ service/endpoint/tls.go | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+) create mode 100644 service/endpoint/tls.go diff --git a/service/endpoint/config.go b/service/endpoint/config.go index 15d71d4..95c7d0e 100644 --- a/service/endpoint/config.go +++ b/service/endpoint/config.go @@ -38,6 +38,8 @@ type Config struct { EnableMemProf bool EnableCPUProf bool + TLS *TLSConfig + AllowedSubnet []string `json:",omitempty" yaml:",omitempty"` } diff --git a/service/endpoint/service.go b/service/endpoint/service.go index b9e60b8..3f33f58 100644 --- a/service/endpoint/service.go +++ b/service/endpoint/service.go @@ -54,6 +54,18 @@ func (s *Service) Listen() (net.Listener, error) { func (s *Service) Serve(l net.Listener) error { log.Printf("starting mly service endpoint: %v\n", s.server.Addr) + tls := s.config.TLS + + var err error + if tls == nil { + err = tls.Valid() + if err != nil { + return err + } + + return s.server.ServeTLS(l, tls.CertFile, tls.KeyFile) + } + return s.server.Serve(l) } diff --git a/service/endpoint/tls.go b/service/endpoint/tls.go new file mode 100644 index 0000000..883f170 --- /dev/null +++ b/service/endpoint/tls.go @@ -0,0 +1,37 @@ +package endpoint + +import ( + "fmt" + "os" +) + +type TLSConfig struct { + CertFile string + KeyFile string +} + +func (t *TLSConfig) Valid() error { + if t.CertFile == "" { + return fmt.Errorf("CertFile not set") + } + + if t.KeyFile == "" { + return fmt.Errorf("KeyFile not set") + } + + fp, err := os.Open(t.CertFile) + if err != nil { + fp.Close() + } else { + return fmt.Errorf("could not open %s, %w", t.CertFile, err) + } + + fp, err = os.Open(t.KeyFile) + if err != nil { + fp.Close() + } else { + return fmt.Errorf("could not open %s, %w", t.KeyFile, err) + } + + return nil +}