Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EVEREST-1180 | TLS support #888

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions cmd/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,11 @@ var (

// EverestConfig stores the configuration for the application.
type EverestConfig struct {
DSN string `default:"postgres://admin:pwd@127.0.0.1:5432/postgres?sslmode=disable" envconfig:"DSN"`
HTTPPort int `default:"8080" envconfig:"HTTP_PORT"`
Verbose bool `default:"false" envconfig:"VERBOSE"`
DSN string `default:"postgres://admin:pwd@127.0.0.1:5432/postgres?sslmode=disable" envconfig:"DSN"`
// DEPRECATED: Use ListenPort instead.
HTTPPort int `envconfig:"HTTP_PORT"`
ListenPort int `default:"8080" envconfig:"PORT"`
Verbose bool `default:"false" envconfig:"VERBOSE"`
// TelemetryURL Everest telemetry endpoint.
TelemetryURL string `envconfig:"TELEMETRY_URL"`
// TelemetryInterval Everest telemetry sending frequency.
Expand All @@ -54,6 +56,9 @@ type EverestConfig struct {
CreateSessionRateLimit int `default:"1" envconfig:"CREATE_SESSION_RATE_LIMIT"`
// VersionServiceURL contains the URL of the version service.
VersionServiceURL string `default:"https://check.percona.com" envconfig:"VERSION_SERVICE_URL"`
// TLSCertsPath contains the path to the directory with the TLS certificates.
// Setting this will enable HTTPS on ListenPort.
TLSCertsPath string `envconfig:"TLS_CERTS_PATH"`
}

// ParseConfig parses env vars and fills EverestConfig.
Expand Down
2 changes: 1 addition & 1 deletion cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func main() {
}

go func() {
err := server.Start()
err := server.Start(tCtx)
if err != nil && !errors.Is(err, http.ErrServerClosed) {
l.Fatal(err)
}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ require (
github.com/cenkalti/backoff v2.2.1+incompatible
github.com/cenkalti/backoff/v4 v4.3.0
github.com/fatih/color v1.18.0
github.com/fsnotify/fsnotify v1.7.0
github.com/getkin/kin-openapi v0.128.0
github.com/go-logr/zapr v1.3.0
github.com/golang-jwt/jwt/v5 v5.2.1
Expand Down Expand Up @@ -103,7 +104,6 @@ require (
github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/flosch/pongo2/v6 v6.0.0 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/fxamacker/cbor/v2 v2.7.0 // indirect
github.com/go-errors/errors v1.5.0 // indirect
github.com/go-gorp/gorp/v3 v3.1.0 // indirect
Expand Down
38 changes: 36 additions & 2 deletions internal/server/everest.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@ package server

import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/fs"
"net/http"
"path"
"slices"

"github.com/getkin/kin-openapi/openapi3filter"
Expand All @@ -42,6 +44,7 @@ import (
k8shandler "github.com/percona/everest/internal/server/handlers/k8s"
rbachandler "github.com/percona/everest/internal/server/handlers/rbac"
valhandler "github.com/percona/everest/internal/server/handlers/validation"
"github.com/percona/everest/pkg/certwatcher"
"github.com/percona/everest/pkg/common"
"github.com/percona/everest/pkg/kubernetes"
"github.com/percona/everest/pkg/oidc"
Expand All @@ -67,6 +70,11 @@ func NewEverestServer(ctx context.Context, c *config.EverestConfig, l *zap.Sugar
return nil, errors.Join(err, errors.New("failed creating Kubernetes client"))
}

if c.HTTPPort != 0 {
l.Warn("HTTP_PORT is deprecated, use PORT instead")
c.ListenPort = c.HTTPPort
}

echoServer := echo.New()
echoServer.Use(echomiddleware.RateLimiter(echomiddleware.NewRateLimiterMemoryStore(rate.Limit(c.APIRequestsRateLimit))))
middleware, store := sessionRateLimiter(c.CreateSessionRateLimit)
Expand Down Expand Up @@ -294,8 +302,34 @@ func newSkipperFunc() (echomiddleware.Skipper, error) {
}

// Start starts everest server.
func (e *EverestServer) Start() error {
return e.echo.Start(fmt.Sprintf("0.0.0.0:%d", e.config.HTTPPort))
func (e *EverestServer) Start(ctx context.Context) error {
addr := fmt.Sprintf("0.0.0.0:%d", e.config.ListenPort)
if e.config.TLSCertsPath != "" {
return e.startHTTPS(ctx, addr)
}
return e.echo.Start(addr)
}

func (e *EverestServer) startHTTPS(ctx context.Context, addr string) error {
tlsKeyPath := path.Join(e.config.TLSCertsPath, "tls.key")
tlsCertPath := path.Join(e.config.TLSCertsPath, "tls.crt")

watcher, err := certwatcher.New(e.l, tlsCertPath, tlsKeyPath)
if err != nil {
return fmt.Errorf("failed to create cert watcher: %w", err)
}
if err := watcher.Start(ctx); err != nil {
return fmt.Errorf("failed to start cert watcher: %w", err)
}

e.echo.TLSServer = &http.Server{
Addr: addr,
TLSConfig: &tls.Config{
// server periodically calls GetCertificate and reloads the certificate.
GetCertificate: watcher.GetCertificate,
},
}
return e.echo.StartServer(e.echo.TLSServer)
}

// Shutdown gracefully stops the Everest server.
Expand Down
79 changes: 79 additions & 0 deletions pkg/certwatcher/watcher.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package certwatcher

import (
"context"
"crypto/tls"
"sync"

"github.com/fsnotify/fsnotify"
"go.uber.org/zap"
)

type certWatcher struct {
cert *tls.Certificate
certFile, keyFile string
log *zap.SugaredLogger

mutex sync.RWMutex
}

// GetCertificate returns the certificate.
func (w *certWatcher) GetCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, error) {
w.mutex.RLock()
defer w.mutex.RUnlock()
return w.cert, nil
}

// New returns a new cert watcher.
func New(log *zap.SugaredLogger, certFile, keyFile string) (*certWatcher, error) {
w := &certWatcher{
certFile: certFile,
keyFile: keyFile,
log: log,
}
if err := w.loadCertificate(); err != nil {
return nil, err
}
return w, nil
}

func (w *certWatcher) loadCertificate() error {
w.mutex.Lock()
defer w.mutex.Unlock()

cert, err := tls.LoadX509KeyPair(w.certFile, w.keyFile)
if err != nil {
return err
}
w.cert = &cert
return nil
}

// Start the certificate files watcher until the context is closed.
func (w *certWatcher) Start(ctx context.Context) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
watcher.Add(w.certFile)
watcher.Add(w.keyFile)

w.log.Infow("Watching certificate files for changes", "certFile", w.certFile, "keyFile", w.keyFile)

go func() {
for {
select {
case <-ctx.Done():
if err := watcher.Close(); err != nil {
w.log.Errorw("Failed to close watcher", "error", err)
}
case <-watcher.Events:
w.log.Info("Certificate updated")
if err := w.loadCertificate(); err != nil {
w.log.Errorw("Failed to reload certificate", "error", err)
}
}
}
}()
return nil
}
Loading