You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by ha...@apache.org on 2025/04/22 10:34:41 UTC
(skywalking-banyandb) branch main updated: Enable Dynamic Reloading of TLS Certificates and Keys (#642)
This is an automated email from the ASF dual-hosted git repository.
hanahmily pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/skywalking-banyandb.git
The following commit(s) were added to refs/heads/main by this push:
new 17bea264 Enable Dynamic Reloading of TLS Certificates and Keys (#642)
17bea264 is described below
commit 17bea264bc3fa89052dd956bdcc156957140e53a
Author: Onkar Raghunath Shelke <14...@users.noreply.github.com>
AuthorDate: Tue Apr 22 16:04:37 2025 +0530
Enable Dynamic Reloading of TLS Certificates and Keys (#642)
* add dynamic TLS certificate and key reloading for automatic reloading of TLS certificates and keys
---------
Co-authored-by: Gao Hongtao <ha...@gmail.com>
---
CHANGES.md | 1 +
banyand/liaison/grpc/server.go | 41 ++-
banyand/liaison/http/rpath_empty.go | 4 +-
banyand/liaison/http/rpath_ui.go | 6 +-
banyand/liaison/http/server.go | 312 +++++++++++++----
banyand/queue/pub/pub_test.go | 3 +-
dist/LICENSE | 2 +-
docs/operation/security.md | 2 +
go.mod | 2 +-
go.sum | 4 +-
pkg/tls/cert_util.go | 75 ++++
pkg/tls/reloader.go | 397 +++++++++++++++++++++
pkg/tls/reloader_test.go | 485 ++++++++++++++++++++++++++
test/integration/standalone/other/tls_test.go | 160 ++++++++-
14 files changed, 1410 insertions(+), 84 deletions(-)
diff --git a/CHANGES.md b/CHANGES.md
index 0da6ead6..0a30303a 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -8,6 +8,7 @@ Release Notes.
- Add sharding_key for TopNAggregation source measure
- API: Update the data matching rule from the node selector to the stage name.
+- Add dynamical TLS load for the gRPC and HTTP server.
### Bug Fixes
diff --git a/banyand/liaison/grpc/server.go b/banyand/liaison/grpc/server.go
index af9ad704..376fc150 100644
--- a/banyand/liaison/grpc/server.go
+++ b/banyand/liaison/grpc/server.go
@@ -46,6 +46,7 @@ import (
"github.com/apache/skywalking-banyandb/banyand/queue"
"github.com/apache/skywalking-banyandb/pkg/logger"
"github.com/apache/skywalking-banyandb/pkg/run"
+ pkgtls "github.com/apache/skywalking-banyandb/pkg/tls"
)
const defaultRecvSize = 10 << 20
@@ -75,11 +76,11 @@ type NodeRegistries struct {
type server struct {
databasev1.UnimplementedSnapshotServiceServer
- creds credentials.TransportCredentials
- omr observability.MetricsRegistry
- measureSVC *measureService
- ser *grpclib.Server
- log *logger.Logger
+ tlsReloader *pkgtls.Reloader
+ omr observability.MetricsRegistry
+ measureSVC *measureService
+ ser *grpclib.Server
+ log *logger.Logger
*propertyServer
*topNAggregationRegistryServer
*groupRegistryServer
@@ -184,6 +185,16 @@ func (s *server) PreRun(_ context.Context) error {
s.groupRegistryServer.metrics = metrics
s.topNAggregationRegistryServer.metrics = metrics
s.propertyRegistryServer.metrics = metrics
+
+ if s.tls {
+ var err error
+ s.tlsReloader, err = pkgtls.NewReloader(s.certFile, s.keyFile, s.log)
+ if err != nil {
+ s.log.Error().Err(err).Msg("Failed to initialize TLSReloader for gRPC")
+ return err
+ }
+ }
+
return nil
}
@@ -232,18 +243,21 @@ func (s *server) Validate() error {
if s.keyFile == "" {
return errServerKey
}
- creds, errTLS := credentials.NewServerTLSFromFile(s.certFile, s.keyFile)
- if errTLS != nil {
- return errors.Wrap(errTLS, "failed to load cert and key")
- }
- s.creds = creds
return nil
}
func (s *server) Serve() run.StopNotify {
var opts []grpclib.ServerOption
if s.tls {
- opts = []grpclib.ServerOption{grpclib.Creds(s.creds)}
+ if err := s.tlsReloader.Start(); err != nil {
+ s.log.Error().Err(err).Msg("Failed to start TLSReloader for gRPC")
+ close(s.stopCh)
+ return s.stopCh
+ }
+ s.log.Info().Str("certFile", s.certFile).Str("keyFile", s.keyFile).Msg("Starting TLS file monitoring")
+ tlsConfig := s.tlsReloader.GetTLSConfig()
+ creds := credentials.NewTLS(tlsConfig)
+ opts = append(opts, grpclib.Creds(creds))
}
grpcPanicRecoveryHandler := func(p any) (err error) {
s.log.Error().Interface("panic", p).Str("stack", string(debug.Stack())).Msg("recovered from panic")
@@ -269,7 +283,6 @@ func (s *server) Serve() run.StopNotify {
commonv1.RegisterServiceServer(s.ser, &apiVersionService{})
streamv1.RegisterStreamServiceServer(s.ser, s.streamSVC)
measurev1.RegisterMeasureServiceServer(s.ser, s.measureSVC)
- // register *Registry
databasev1.RegisterGroupRegistryServiceServer(s.ser, s.groupRegistryServer)
databasev1.RegisterIndexRuleBindingRegistryServiceServer(s.ser, s.indexRuleBindingRegistryServer)
databasev1.RegisterIndexRuleRegistryServiceServer(s.ser, s.indexRuleRegistryServer)
@@ -282,6 +295,7 @@ func (s *server) Serve() run.StopNotify {
grpc_health_v1.RegisterHealthServer(s.ser, health.NewServer())
s.stopCh = make(chan struct{})
+ s.log.Info().Str("addr", s.addr).Msg("Starting gRPC server")
go func() {
lis, err := net.Listen("tcp", s.addr)
if err != nil {
@@ -301,6 +315,9 @@ func (s *server) Serve() run.StopNotify {
func (s *server) GracefulStop() {
s.log.Info().Msg("stopping")
+ if s.tls && s.tlsReloader != nil {
+ s.tlsReloader.Stop()
+ }
stopped := make(chan struct{})
go func() {
s.ser.GracefulStop()
diff --git a/banyand/liaison/http/rpath_empty.go b/banyand/liaison/http/rpath_empty.go
index d126093d..ed187d49 100644
--- a/banyand/liaison/http/rpath_empty.go
+++ b/banyand/liaison/http/rpath_empty.go
@@ -20,6 +20,8 @@
package http
-func (p *server) setRootPath() error {
+import "github.com/go-chi/chi/v5"
+
+func (p *server) setRootPath(_ *chi.Mux) error {
return nil
}
diff --git a/banyand/liaison/http/rpath_ui.go b/banyand/liaison/http/rpath_ui.go
index 460239a2..3454e493 100644
--- a/banyand/liaison/http/rpath_ui.go
+++ b/banyand/liaison/http/rpath_ui.go
@@ -24,10 +24,12 @@ import (
"io/fs"
"net/http"
+ "github.com/go-chi/chi/v5"
+
"github.com/apache/skywalking-banyandb/ui"
)
-func (p *server) setRootPath() error {
+func (p *server) setRootPath(mux *chi.Mux) error {
fSys, err := fs.Sub(ui.DistContent, "dist")
if err != nil {
return err
@@ -35,6 +37,6 @@ func (p *server) setRootPath() error {
httpFS := http.FS(fSys)
fileServer := http.FileServer(http.FS(fSys))
serveIndex := serveFileContents("index.html", httpFS)
- p.mux.Mount("/", intercept404(fileServer, serveIndex))
+ mux.Mount("/", intercept404(fileServer, serveIndex))
return nil
}
diff --git a/banyand/liaison/http/server.go b/banyand/liaison/http/server.go
index 1e6bc744..fae89336 100644
--- a/banyand/liaison/http/server.go
+++ b/banyand/liaison/http/server.go
@@ -25,6 +25,7 @@ import (
"net/http"
"strconv"
"strings"
+ "sync/atomic"
"time"
"github.com/go-chi/chi/v5"
@@ -43,6 +44,7 @@ import (
"github.com/apache/skywalking-banyandb/pkg/healthcheck"
"github.com/apache/skywalking-banyandb/pkg/logger"
"github.com/apache/skywalking-banyandb/pkg/run"
+ pkgtls "github.com/apache/skywalking-banyandb/pkg/tls"
)
var (
@@ -68,20 +70,25 @@ type Server interface {
}
type server struct {
- creds credentials.TransportCredentials
- l *logger.Logger
- clientCloser context.CancelFunc
- mux *chi.Mux
- srv *http.Server
- stopCh chan struct{}
- host string
- listenAddr string
- grpcAddr string
- keyFile string
- certFile string
- grpcCert string
- port uint32
- tls bool
+ creds credentials.TransportCredentials
+ tlsReloader *pkgtls.Reloader
+ grpcTLSReloader *pkgtls.Reloader
+ l *logger.Logger
+ handlerWrapper *atomicHandler
+ srv *http.Server
+ stopCh chan struct{}
+ gwMux *runtime.ServeMux
+ grpcClient *healthcheck.Client
+ grpcCtx context.Context
+ grpcCancel context.CancelFunc
+ host string
+ listenAddr string
+ grpcAddr string
+ keyFile string
+ certFile string
+ grpcCert string
+ port uint32
+ tls bool
}
func (p *server) FlagSet() *run.FlagSet {
@@ -101,13 +108,6 @@ func (p *server) Validate() error {
if p.listenAddr == ":" {
return errNoAddr
}
- if p.grpcCert != "" {
- creds, errTLS := credentials.NewClientTLSFromFile(p.grpcCert, "")
- if errTLS != nil {
- return errors.Wrap(errTLS, "failed to load the grpc cert")
- }
- p.creds = creds
- }
if !p.tls {
return nil
}
@@ -134,77 +134,250 @@ func (p *server) GetPort() *uint32 {
func (p *server) PreRun(_ context.Context) error {
p.l = logger.GetLogger(p.Name())
- p.mux = chi.NewRouter()
+ p.l.Info().Str("level", p.l.GetLevel().String()).Msg("Logger initialized")
- if err := p.setRootPath(); err != nil {
- return err
+ // Log flag values after parsing
+ p.l.Debug().Bool("tls", p.tls).Str("certFile", p.certFile).Str("keyFile", p.keyFile).Msg("Flag values after parsing")
+
+ // Initialize TLSReloader if TLS is enabled
+ p.l.Debug().Bool("tls", p.tls).Msg("HTTP TLS flag is set")
+ if p.tls {
+ p.l.Debug().Str("certFile", p.certFile).Str("keyFile", p.keyFile).Msg("Initializing TLSReloader for HTTP")
+ var err error
+ p.tlsReloader, err = pkgtls.NewReloader(p.certFile, p.keyFile, p.l)
+ if err != nil {
+ p.l.Error().Err(err).Msg("Failed to initialize TLSReloader for HTTP")
+ return err
+ }
+ } else {
+ p.l.Warn().Msg("HTTP TLS is disabled, skipping TLSReloader initialization")
+ }
+
+ // Initialize gRPC client with cert file
+ if p.grpcCert != "" {
+ p.l.Debug().Str("grpcCert", p.grpcCert).Msg("Initializing TLS credentials for gRPC connection")
+
+ // Create a client cert reloader that only watches the cert file
+ var err error
+ p.grpcTLSReloader, err = pkgtls.NewClientCertReloader(p.grpcCert, p.l)
+ if err != nil {
+ p.l.Error().Err(err).Msg("Failed to initialize gRPC TLS reloader")
+ return err
+ }
+
+ // Start the reloader
+ if err = p.grpcTLSReloader.Start(); err != nil {
+ p.l.Error().Err(err).Msg("Failed to start gRPC TLS reloader")
+ return err
+ }
+
+ // Get the update channel from the reloader
+ certUpdateCh := p.grpcTLSReloader.GetUpdateChannel()
+
+ p.l.Info().Msg("Starting certificate update notification listener")
+
+ // Start a goroutine to watch for certificate update events
+ go func() {
+ p.l.Info().Msg("Certificate update notification goroutine started")
+
+ for {
+ select {
+ case <-certUpdateCh:
+ // Certificate was updated, let's debounce to handle potential multiple notifications
+ p.l.Info().Msg("Received certificate update notification")
+
+ // Debounce multiple notifications that might come in rapid succession
+ func() {
+ p.l.Info().Msg("Processing certificate update after debounce")
+
+ // Cancel existing gRPC connections
+ prevGRPCCancel := p.grpcCancel
+ if prevGRPCCancel != nil {
+ defer func() {
+ p.l.Info().Msg("Canceling existing gRPC connections")
+ prevGRPCCancel()
+ }()
+ }
+
+ // Create a new context for the new connections
+ p.grpcCtx, p.grpcCancel = context.WithCancel(context.Background())
+
+ // Force a short delay to ensure all resources are properly cleaned up
+ time.Sleep(200 * time.Millisecond)
+
+ // Re-create the gateway with updated credentials
+ if p.gwMux != nil {
+ p.l.Info().Msg("Re-creating gateway with updated credentials")
+ }
+
+ // Reinitialize the gRPC client (which will get fresh credentials from the reloader)
+ if err := p.initGRPCClient(); err != nil {
+ p.l.Error().Err(err).Msg("Failed to reinitialize gRPC client after credential update")
+ } else {
+ p.l.Info().Msg("Successfully reinitialized gRPC client with new credentials")
+ }
+ }()
+
+ case <-p.stopCh:
+ p.l.Info().Msg("Stopping certificate update notification listener")
+ return
+ }
+ }
+ }()
}
+
+ p.handlerWrapper = &atomicHandler{}
+
+ // Configure the HTTP server with dynamic TLS if enabled
p.srv = &http.Server{
Addr: p.listenAddr,
- Handler: p.mux,
+ Handler: p.handlerWrapper,
ReadHeaderTimeout: 3 * time.Second,
+ WriteTimeout: 30 * time.Second,
+ IdleTimeout: 60 * time.Second,
+ }
+ if p.tls {
+ p.srv.TLSConfig = p.tlsReloader.GetTLSConfig()
}
+
return nil
}
func (p *server) Serve() run.StopNotify {
- var ctx context.Context
- ctx, p.clientCloser = context.WithCancel(context.Background())
- opts := make([]grpc.DialOption, 0, 1)
- if p.creds == nil {
- opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
- } else {
- opts = append(opts, grpc.WithTransportCredentials(p.creds))
- }
- client, err := healthcheck.NewClient(ctx, p.l, p.grpcAddr, opts)
- if err != nil {
- p.l.Error().Err(err).Msg("Failed to health check client")
- close(p.stopCh)
- return p.stopCh
+ p.grpcCtx, p.grpcCancel = context.WithCancel(context.Background())
+
+ // Start TLS reloader for HTTP server
+ if p.tls && p.tlsReloader != nil {
+ if err := p.tlsReloader.Start(); err != nil {
+ p.l.Error().Err(err).Msg("Failed to start TLSReloader for HTTP")
+ close(p.stopCh)
+ return p.stopCh
+ }
}
- gwMux := runtime.NewServeMux(runtime.WithHealthzEndpoint(client))
- err = multierr.Combine(
- commonv1.RegisterServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
- databasev1.RegisterStreamRegistryServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
- databasev1.RegisterMeasureRegistryServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
- databasev1.RegisterIndexRuleRegistryServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
- databasev1.RegisterIndexRuleBindingRegistryServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
- databasev1.RegisterGroupRegistryServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
- databasev1.RegisterTopNAggregationRegistryServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
- databasev1.RegisterSnapshotServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
- databasev1.RegisterPropertyRegistryServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
- streamv1.RegisterStreamServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
- measurev1.RegisterMeasureServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
- propertyv1.RegisterPropertyServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
- )
- if err != nil {
- p.l.Error().Err(err).Msg("Failed to register endpoints")
+
+ // Initialize gRPC client and gateway mux
+ if err := p.initGRPCClient(); err != nil {
+ p.l.Error().Err(err).Msg("Failed to initialize gRPC client")
close(p.stopCh)
return p.stopCh
}
- p.mux.Mount("/api", http.StripPrefix("/api", gwMux))
+
go func() {
+ defer close(p.stopCh)
p.l.Info().Str("listenAddr", p.listenAddr).Msg("Start liaison http server")
var err error
if p.tls {
- err = p.srv.ListenAndServeTLS(p.certFile, p.keyFile)
+ // Start the TLSReloader file monitoring already done above
+ // Use TLS with dynamic certificate loading
+ err = p.srv.ListenAndServeTLS("", "") // Empty strings because TLSConfig is set
} else {
err = p.srv.ListenAndServe()
}
if err != http.ErrServerClosed {
- p.l.Error().Err(err)
+ p.l.Error().Err(err).Msg("HTTP server failed")
}
-
- close(p.stopCh)
}()
return p.stopCh
}
+// initGRPCClient initializes or reinitializes the gRPC client with current credentials.
+func (p *server) initGRPCClient() error {
+ // Clean up any existing client first
+ if p.grpcClient != nil {
+ p.l.Debug().Msg("Cleaning up existing gRPC client")
+ }
+
+ // Simplify the options slice initialization
+ var opts []grpc.DialOption
+
+ // Use switch statement instead of if-else chain
+ switch {
+ case p.grpcTLSReloader != nil:
+ // Extract hostname from grpcAddr
+ host, _, err := net.SplitHostPort(p.grpcAddr)
+ if err != nil {
+ p.l.Error().Err(err).Msg("Failed to split gRPC address")
+ return errors.Wrap(err, "failed to split gRPC address")
+ }
+ if host == "" || host == "0.0.0.0" || host == "[::]" {
+ host = "localhost"
+ }
+
+ // Get fresh TLS config from the reloader
+ tlsConfig, err := p.grpcTLSReloader.GetClientTLSConfig(host)
+ if err != nil {
+ p.l.Error().Err(err).Msg("Failed to get TLS config from reloader")
+ return errors.Wrap(err, "failed to get TLS config from reloader")
+ }
+
+ // Create new credentials from the TLS config
+ p.creds = credentials.NewTLS(tlsConfig)
+ p.l.Debug().Msg("Created fresh gRPC credentials from reloader")
+ opts = append(opts, grpc.WithTransportCredentials(p.creds))
+ case p.creds != nil:
+ opts = append(opts, grpc.WithTransportCredentials(p.creds))
+ default:
+ opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
+ }
+
+ // Create health check client
+ var err error
+ p.grpcClient, err = healthcheck.NewClient(p.grpcCtx, p.l, p.grpcAddr, opts)
+ if err != nil {
+ return errors.Wrap(err, "failed to create health check client")
+ }
+
+ // Create gateway mux with health endpoint
+ p.gwMux = runtime.NewServeMux(runtime.WithHealthzEndpoint(p.grpcClient))
+
+ // Register all service handlers
+ err = multierr.Combine(
+ commonv1.RegisterServiceHandlerFromEndpoint(p.grpcCtx, p.gwMux, p.grpcAddr, opts),
+ databasev1.RegisterStreamRegistryServiceHandlerFromEndpoint(p.grpcCtx, p.gwMux, p.grpcAddr, opts),
+ databasev1.RegisterMeasureRegistryServiceHandlerFromEndpoint(p.grpcCtx, p.gwMux, p.grpcAddr, opts),
+ databasev1.RegisterIndexRuleRegistryServiceHandlerFromEndpoint(p.grpcCtx, p.gwMux, p.grpcAddr, opts),
+ databasev1.RegisterIndexRuleBindingRegistryServiceHandlerFromEndpoint(p.grpcCtx, p.gwMux, p.grpcAddr, opts),
+ databasev1.RegisterGroupRegistryServiceHandlerFromEndpoint(p.grpcCtx, p.gwMux, p.grpcAddr, opts),
+ databasev1.RegisterTopNAggregationRegistryServiceHandlerFromEndpoint(p.grpcCtx, p.gwMux, p.grpcAddr, opts),
+ databasev1.RegisterSnapshotServiceHandlerFromEndpoint(p.grpcCtx, p.gwMux, p.grpcAddr, opts),
+ databasev1.RegisterPropertyRegistryServiceHandlerFromEndpoint(p.grpcCtx, p.gwMux, p.grpcAddr, opts),
+ streamv1.RegisterStreamServiceHandlerFromEndpoint(p.grpcCtx, p.gwMux, p.grpcAddr, opts),
+ measurev1.RegisterMeasureServiceHandlerFromEndpoint(p.grpcCtx, p.gwMux, p.grpcAddr, opts),
+ propertyv1.RegisterPropertyServiceHandlerFromEndpoint(p.grpcCtx, p.gwMux, p.grpcAddr, opts),
+ )
+ if err != nil {
+ return errors.Wrap(err, "failed to register endpoints")
+ }
+
+ // Create a new router to replace the existing one
+ // This avoids the conflict when remounting to /api path
+ newMux := chi.NewRouter()
+
+ // Mount the gateway mux to the HTTP server
+ newMux.Mount("/api", http.StripPrefix("/api", p.gwMux))
+
+ // Replace the old mux with the new one
+ if err := p.setRootPath(newMux); err != nil {
+ return err
+ }
+ p.handlerWrapper.Store(newMux)
+
+ return nil
+}
+
func (p *server) GracefulStop() {
+ if p.tlsReloader != nil {
+ p.tlsReloader.Stop()
+ }
+ if p.grpcTLSReloader != nil {
+ p.grpcTLSReloader.Stop()
+ }
+ if p.grpcCancel != nil {
+ p.grpcCancel()
+ }
if err := p.srv.Close(); err != nil {
p.l.Error().Err(err)
}
- p.clientCloser()
}
func intercept404(handler, on404 http.Handler) http.HandlerFunc {
@@ -265,3 +438,20 @@ func serveFileContents(file string, files http.FileSystem) http.HandlerFunc {
http.ServeContent(w, r, fi.Name(), fi.ModTime(), index)
}
}
+
+type atomicHandler struct {
+ value atomic.Value // stores http.Handler
+}
+
+func (h *atomicHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ handler, ok := h.value.Load().(http.Handler)
+ if ok && handler != nil {
+ handler.ServeHTTP(w, r)
+ } else {
+ http.NotFound(w, r)
+ }
+}
+
+func (h *atomicHandler) Store(handler http.Handler) {
+ h.value.Store(handler)
+}
diff --git a/banyand/queue/pub/pub_test.go b/banyand/queue/pub/pub_test.go
index 5bd525e8..daaf2505 100644
--- a/banyand/queue/pub/pub_test.go
+++ b/banyand/queue/pub/pub_test.go
@@ -216,7 +216,8 @@ var _ = ginkgo.Describe("Publish and Broadcast", func() {
node2 := getDataNode("node2", addr2)
p.OnAddOrUpdate(node2)
- ff, err := p.Broadcast(3*time.Second, data.TopicStreamQuery, bus.NewMessage(bus.MessageID(1), &streamv1.QueryRequest{}))
+ req := &streamv1.QueryRequest{}
+ ff, err := p.Broadcast(3*time.Second, data.TopicStreamQuery, bus.NewMessage(bus.MessageID(1), req))
gomega.Expect(err).ShouldNot(gomega.HaveOccurred())
gomega.Expect(ff).Should(gomega.HaveLen(2))
messages, err := ff[0].GetAll()
diff --git a/dist/LICENSE b/dist/LICENSE
index 8e7d0a6d..09cc4a48 100644
--- a/dist/LICENSE
+++ b/dist/LICENSE
@@ -262,7 +262,7 @@ BSD-3-Clause licenses
github.com/bits-and-blooms/bitset v1.22.0 BSD-3-Clause
github.com/blevesearch/mmap-go v1.0.4 BSD-3-Clause
github.com/blevesearch/snowballstem v0.9.0 BSD-3-Clause
- github.com/fsnotify/fsnotify v1.8.0 BSD-3-Clause
+ github.com/fsnotify/fsnotify v1.9.0 BSD-3-Clause
github.com/gogo/protobuf v1.3.2 BSD-3-Clause
github.com/golang/protobuf v1.5.4 BSD-3-Clause
github.com/golang/snappy v1.0.0 BSD-3-Clause
diff --git a/docs/operation/security.md b/docs/operation/security.md
index 3ea84191..df070992 100644
--- a/docs/operation/security.md
+++ b/docs/operation/security.md
@@ -34,6 +34,8 @@ banyand liaison --http-tls=true --http-key-file=server.key --http-cert-file=serv
> Note: BanyanDB does not support TLS between liaison and data nodes.
+The key and certificate files can be reloaded automatically when they are updated. You can update the files or recreate the files, and the server will automatically reload them.
+
## Authorization
BanyanDB does not have built-in authorization mechanisms. However, you can use external tools like [Envoy](https://www.envoyproxy.io/) or [Istio](https://istio.io/) to manage access control and authorization.
diff --git a/go.mod b/go.mod
index 2486b37a..3d780cde 100644
--- a/go.mod
+++ b/go.mod
@@ -80,7 +80,7 @@ require (
github.com/dchest/siphash v1.2.3 // indirect
github.com/dgryski/go-metro v0.0.0-20250106013310-edb8663e5e33 // indirect
github.com/dustin/go-humanize v1.0.1
- github.com/fsnotify/fsnotify v1.8.0 // indirect
+ github.com/fsnotify/fsnotify v1.9.0
github.com/go-logr/logr v1.4.2 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
diff --git a/go.sum b/go.sum
index 8b2cda74..ea30643a 100644
--- a/go.sum
+++ b/go.sum
@@ -82,8 +82,8 @@ github.com/envoyproxy/protoc-gen-validate v1.2.1 h1:DEo3O99U8j4hBFwbJfrz9VtgcDfU
github.com/envoyproxy/protoc-gen-validate v1.2.1/go.mod h1:d/C80l/jxXLdfEIhX1W2TmLfsJ31lvEjwamM4DxlWXU=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
-github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
-github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
+github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
+github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/go-chi/chi/v5 v5.2.1 h1:KOIHODQj58PmL80G2Eak4WdvUzjSJSm0vG72crDCqb8=
github.com/go-chi/chi/v5 v5.2.1/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
diff --git a/pkg/tls/cert_util.go b/pkg/tls/cert_util.go
new file mode 100644
index 00000000..e1a51aef
--- /dev/null
+++ b/pkg/tls/cert_util.go
@@ -0,0 +1,75 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package tls
+
+import (
+ "crypto/rand"
+ "crypto/rsa"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/pem"
+ "math/big"
+ "time"
+)
+
+// GenerateSelfSignedCert creates a new self-signed certificate for testing purposes.
+// It returns the certificate PEM, key PEM, and any error that occurred.
+func GenerateSelfSignedCert(commonName string, extraDNSNames []string) (certPEM, keyPEM []byte, err error) {
+ privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ // Always include the commonName as a DNS name
+ dnsNames := []string{commonName}
+
+ // Add extra DNS names if provided
+ if len(extraDNSNames) > 0 {
+ dnsNames = append(dnsNames, extraDNSNames...)
+ }
+
+ template := x509.Certificate{
+ SerialNumber: big.NewInt(1),
+ Subject: pkix.Name{
+ CommonName: commonName,
+ },
+ DNSNames: dnsNames,
+ NotBefore: time.Now(),
+ NotAfter: time.Now().Add(time.Hour * 24),
+ KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+ BasicConstraintsValid: true,
+ }
+
+ certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ certPEM = pem.EncodeToMemory(&pem.Block{
+ Type: "CERTIFICATE",
+ Bytes: certDER,
+ })
+
+ keyPEM = pem.EncodeToMemory(&pem.Block{
+ Type: "RSA PRIVATE KEY",
+ Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
+ })
+
+ return certPEM, keyPEM, nil
+}
diff --git a/pkg/tls/reloader.go b/pkg/tls/reloader.go
new file mode 100644
index 00000000..9f8a457d
--- /dev/null
+++ b/pkg/tls/reloader.go
@@ -0,0 +1,397 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Package tls provides common TLS utilities for HTTP and gRPC servers.
+package tls
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "crypto/tls"
+ "crypto/x509"
+ "os"
+ "sync"
+ "time"
+
+ "github.com/fsnotify/fsnotify"
+ "github.com/pkg/errors"
+
+ "github.com/apache/skywalking-banyandb/pkg/logger"
+)
+
+// Reloader manages dynamic reloading of TLS certificates and keys for servers.
+//
+//nolint:govet
+type Reloader struct {
+ cert *tls.Certificate
+ watcher *fsnotify.Watcher
+ log *logger.Logger
+ debounceTimer *time.Timer
+ updateCh chan struct{}
+ certFile string
+ keyFile string
+ lastCertHash []byte
+ lastKeyHash []byte
+ mu sync.RWMutex
+}
+
+// NewReloader creates a new TLSReloader instance.
+func NewReloader(certFile, keyFile string, log *logger.Logger) (*Reloader, error) {
+ if certFile == "" || keyFile == "" {
+ return nil, errors.New("certFile and keyFile must be provided")
+ }
+ if log == nil {
+ return nil, errors.New("logger must not be nil")
+ }
+
+ watcher, err := fsnotify.NewWatcher()
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to create fsnotify watcher")
+ }
+
+ cert, err := tls.LoadX509KeyPair(certFile, keyFile)
+ if err != nil {
+ watcher.Close()
+ return nil, errors.Wrap(err, "failed to load initial TLS certificate")
+ }
+
+ log.Info().Str("certFile", certFile).Str("keyFile", keyFile).Msg("Successfully loaded initial TLS certificates")
+
+ tr := &Reloader{
+ certFile: certFile,
+ keyFile: keyFile,
+ cert: &cert,
+ log: log,
+ watcher: watcher,
+ updateCh: make(chan struct{}, 1),
+ }
+
+ // Compute initial hashes
+ tr.lastCertHash, _ = tr.computeFileHash(certFile)
+ if keyFile != "" {
+ tr.lastKeyHash, _ = tr.computeFileHash(keyFile)
+ }
+
+ return tr, nil
+}
+
+// NewClientCertReloader creates a reloader that only monitors a CA certificate without requiring a key.
+// This is useful for client-side certificate verification where only the CA cert is needed.
+func NewClientCertReloader(certFile string, log *logger.Logger) (*Reloader, error) {
+ if certFile == "" {
+ return nil, errors.New("certFile must be provided")
+ }
+ if log == nil {
+ return nil, errors.New("logger must not be nil")
+ }
+
+ watcher, err := fsnotify.NewWatcher()
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to create fsnotify watcher")
+ }
+
+ // Read the cert file content to ensure it exists and is valid
+ certPEM, err := os.ReadFile(certFile)
+ if err != nil {
+ watcher.Close()
+ return nil, errors.Wrap(err, "failed to read certificate file")
+ }
+
+ // Ensure the certificate is parsable
+ certPool := x509.NewCertPool()
+ if !certPool.AppendCertsFromPEM(certPEM) {
+ watcher.Close()
+ return nil, errors.New("failed to parse PEM certificate")
+ }
+
+ log.Info().Str("certFile", certFile).Msg("Successfully loaded initial client certificate")
+
+ tr := &Reloader{
+ certFile: certFile,
+ keyFile: "", // No key file for client certs
+ log: log,
+ watcher: watcher,
+ updateCh: make(chan struct{}, 1),
+ }
+
+ // Compute initial cert hash
+ tr.lastCertHash, _ = tr.computeFileHash(certFile)
+
+ return tr, nil
+}
+
+// Start begins monitoring the TLS certificate and key files for changes.
+func (r *Reloader) Start() error {
+ r.log.Info().Str("certFile", r.certFile).Str("keyFile", r.keyFile).Msg("Starting TLS file monitoring")
+
+ err := r.watcher.Add(r.certFile)
+ if err != nil {
+ return errors.Wrapf(err, "failed to watch cert file: %s", r.certFile)
+ }
+
+ // Only add key file watcher if a key file was provided
+ if r.keyFile != "" {
+ err = r.watcher.Add(r.keyFile)
+ if err != nil {
+ return errors.Wrapf(err, "failed to watch key file: %s", r.keyFile)
+ }
+ }
+
+ go r.watchFiles()
+
+ return nil
+}
+
+// computeFileHash calculates a SHA-256 hash of a file's contents.
+func (r *Reloader) computeFileHash(filePath string) ([]byte, error) {
+ content, err := os.ReadFile(filePath)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to read file for hashing: %s", filePath)
+ }
+
+ h := sha256.New()
+ h.Write(content)
+ return h.Sum(nil), nil
+}
+
+// scheduleReloadAttempt debounces reload attempts to avoid excessive reloads.
+func (r *Reloader) scheduleReloadAttempt() {
+ // Create or reset the debounce timer
+ if r.debounceTimer == nil {
+ r.debounceTimer = time.AfterFunc(500*time.Millisecond, func() {
+ // Check if content has changed before reloading
+ changed, newCertHash, newKeyHash, err := r.checkContentChanged()
+ if err != nil {
+ r.log.Error().Err(err).Msg("Error checking if certificate content changed")
+ return
+ }
+
+ if !changed {
+ r.log.Debug().Msg("Certificate content unchanged, skipping reload")
+ return
+ }
+
+ // Content has changed, reload certificate
+ if err := r.reloadCertificate(newCertHash, newKeyHash); err != nil {
+ r.log.Error().Err(err).Msg("Failed to reload TLS certificate")
+ } else {
+ r.log.Info().Msg("Successfully updated TLS certificate after content change")
+ }
+ })
+ } else {
+ r.debounceTimer.Reset(500 * time.Millisecond)
+ }
+}
+
+// checkContentChanged checks if file contents have changed and returns new hashes.
+func (r *Reloader) checkContentChanged() (bool, []byte, []byte, error) {
+ // Check if cert file has changed
+ currentCertHash, err := r.computeFileHash(r.certFile)
+ if err != nil {
+ return false, nil, nil, errors.Wrap(err, "failed to compute current cert hash")
+ }
+
+ certChanged := !bytes.Equal(r.lastCertHash, currentCertHash)
+
+ // If no key file, return just cert info
+ if r.keyFile == "" {
+ return certChanged, currentCertHash, nil, nil
+ }
+
+ // Check if key file has changed
+ currentKeyHash, err := r.computeFileHash(r.keyFile)
+ if err != nil {
+ return false, nil, nil, errors.Wrap(err, "failed to compute current key hash")
+ }
+
+ keyChanged := !bytes.Equal(r.lastKeyHash, currentKeyHash)
+
+ return certChanged || keyChanged, currentCertHash, currentKeyHash, nil
+}
+
+func (r *Reloader) watchFiles() {
+ r.log.Info().Msg("TLS file watcher loop started")
+ for {
+ select {
+ case event, ok := <-r.watcher.Events:
+ if !ok {
+ r.log.Info().Msg("Watcher events channel closed")
+ return
+ }
+
+ r.log.Debug().Str("file", event.Name).Str("op", event.Op.String()).Msg("Detected file event")
+
+ // Handle all relevant file operation events
+ if event.Op&(fsnotify.Remove|fsnotify.Create|fsnotify.Write|fsnotify.Rename) != 0 {
+ // Special handling for removal/creation
+ if event.Op&(fsnotify.Remove|fsnotify.Create) != 0 {
+ r.log.Info().Str("file", event.Name).Msg("File removed or created, waiting for stability")
+
+ // Remove from watcher first to avoid duplicate watches
+ _ = r.watcher.Remove(event.Name)
+
+ // Wait for file operations to complete
+ time.Sleep(200 * time.Millisecond)
+
+ // Try to re-add files to watcher with retries
+ maxRetries := 3
+ for i := 0; i < maxRetries; i++ {
+ if event.Name == r.certFile {
+ if _, err := os.Stat(r.certFile); err == nil {
+ if err := r.watcher.Add(r.certFile); err != nil {
+ r.log.Error().Err(err).Str("file", r.certFile).Msg("Failed to re-add cert file to watcher")
+ } else {
+ r.log.Debug().Str("file", r.certFile).Msg("Re-added cert file to watcher")
+ break
+ }
+ }
+ } else if event.Name == r.keyFile {
+ if _, err := os.Stat(r.keyFile); err == nil {
+ if err := r.watcher.Add(r.keyFile); err != nil {
+ r.log.Error().Err(err).Str("file", r.keyFile).Msg("Failed to re-add key file to watcher")
+ } else {
+ r.log.Debug().Str("file", r.keyFile).Msg("Re-added key file to watcher")
+ break
+ }
+ }
+ }
+ if i < maxRetries-1 {
+ time.Sleep(100 * time.Millisecond)
+ }
+ }
+ } else {
+ r.log.Info().Str("file", event.Name).Msg("Detected certificate modification")
+ time.Sleep(200 * time.Millisecond) // Ensure file is fully written
+ }
+
+ // Schedule a reload attempt with debouncing for all types of events
+ r.scheduleReloadAttempt()
+ }
+
+ case err, ok := <-r.watcher.Errors:
+ if !ok {
+ r.log.Info().Msg("Watcher errors channel closed")
+ return
+ }
+ r.log.Error().Err(err).Msg("Error in file watcher")
+ }
+ }
+}
+
+// notifyUpdate sends update notification to the update channel.
+func (r *Reloader) notifyUpdate() {
+ select {
+ case r.updateCh <- struct{}{}:
+ r.log.Debug().Msg("Sent certificate update notification")
+ default:
+ r.log.Warn().Msg("Update channel is full, notification skipped")
+ }
+}
+
+// reloadCertificate reloads the certificate from disk.
+func (r *Reloader) reloadCertificate(newCertHash, newKeyHash []byte) error {
+ r.log.Debug().Msg("Reloading TLS certificate")
+
+ // For client certificates (no key file), just verify the certificate is valid
+ if r.keyFile == "" {
+ certPEM, err := os.ReadFile(r.certFile)
+ if err != nil {
+ return errors.Wrap(err, "failed to read certificate file")
+ }
+
+ certPool := x509.NewCertPool()
+ if !certPool.AppendCertsFromPEM(certPEM) {
+ return errors.New("failed to parse PEM certificate")
+ }
+
+ // Update the stored hash
+ r.lastCertHash = newCertHash
+
+ r.log.Debug().Msg("Client certificate updated in memory")
+ r.notifyUpdate()
+ return nil
+ }
+
+ // For server certificates with key files, load the key pair
+ newCert, err := tls.LoadX509KeyPair(r.certFile, r.keyFile)
+ if err != nil {
+ return errors.Wrap(err, "failed to reload TLS certificate")
+ }
+
+ // Update certificate and hashes
+ r.mu.Lock()
+ r.cert = &newCert
+ r.lastCertHash = newCertHash
+ r.lastKeyHash = newKeyHash
+ r.mu.Unlock()
+
+ r.log.Debug().Msg("TLS certificate updated in memory")
+ r.notifyUpdate()
+ return nil
+}
+
+// getCertificate returns the current certificate.
+func (r *Reloader) getCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, error) {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ return r.cert, nil
+}
+
+// GetUpdateChannel returns a channel that will be triggered when a certificate is updated.
+func (r *Reloader) GetUpdateChannel() <-chan struct{} {
+ return r.updateCh
+}
+
+// Stop gracefully stops the TLS reloader.
+func (r *Reloader) Stop() {
+ r.log.Info().Msg("Stopping TLS Reloader")
+
+ if err := r.watcher.Close(); err != nil {
+ r.log.Error().Err(err).Msg("Failed to close fsnotify watcher")
+ }
+}
+
+// GetTLSConfig returns a TLS config using this reloader's certificate.
+func (r *Reloader) GetTLSConfig() *tls.Config {
+ return &tls.Config{
+ GetCertificate: r.getCertificate,
+ MinVersion: tls.VersionTLS12,
+ NextProtos: []string{"h2"},
+ }
+}
+
+// GetClientTLSConfig returns a TLS config for client-side certificate validation.
+func (r *Reloader) GetClientTLSConfig(serverName string) (*tls.Config, error) {
+ // Read the certificate file
+ certPEM, err := os.ReadFile(r.certFile)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to read certificate file")
+ }
+
+ // Create a certificate pool
+ certPool := x509.NewCertPool()
+ if !certPool.AppendCertsFromPEM(certPEM) {
+ return nil, errors.New("failed to parse PEM certificate")
+ }
+
+ // Create TLS config for client
+ return &tls.Config{
+ RootCAs: certPool,
+ ServerName: serverName,
+ MinVersion: tls.VersionTLS12,
+ }, nil
+}
diff --git a/pkg/tls/reloader_test.go b/pkg/tls/reloader_test.go
new file mode 100644
index 00000000..4a6483c6
--- /dev/null
+++ b/pkg/tls/reloader_test.go
@@ -0,0 +1,485 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package tls
+
+import (
+ "crypto/tls"
+ "crypto/x509"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/grpc/credentials"
+
+ "github.com/apache/skywalking-banyandb/pkg/logger"
+ "github.com/apache/skywalking-banyandb/pkg/test/flags"
+)
+
+// TestReloaderBasic tests the basic functionality of creating a TLS reloader.
+func TestReloaderBasic(t *testing.T) {
+ // Test with valid certificate and key files
+ t.Run("valid certificate and key", func(t *testing.T) {
+ tempDir := t.TempDir()
+ certFile := filepath.Join(tempDir, "cert.pem")
+ keyFile := filepath.Join(tempDir, "key.pem")
+
+ // Create valid certificate files
+ certPEM, keyPEM, err := GenerateSelfSignedCert("test.local", []string{"test.local"})
+ require.NoError(t, err)
+ require.NoError(t, os.WriteFile(certFile, certPEM, 0o600))
+ require.NoError(t, os.WriteFile(keyFile, keyPEM, 0o600))
+
+ log := logger.GetLogger("tls-test")
+ reloader, err := NewReloader(certFile, keyFile, log)
+ require.NoError(t, err)
+ require.NotNil(t, reloader)
+
+ // Start the reloader
+ require.NoError(t, reloader.Start())
+ defer reloader.Stop()
+ })
+
+ // Test invalid inputs
+ t.Run("error cases", func(t *testing.T) {
+ log := logger.GetLogger("tls-test")
+
+ // Empty paths
+ reloader, err := NewReloader("", "", log)
+ assert.Error(t, err)
+ assert.Nil(t, reloader)
+
+ // Non-existent files
+ reloader, err = NewReloader("nonexistent.pem", "nonexistent.pem", log)
+ assert.Error(t, err)
+ assert.Nil(t, reloader)
+
+ // Nil logger
+ tempDir := t.TempDir()
+ certFile := filepath.Join(tempDir, "cert.pem")
+ keyFile := filepath.Join(tempDir, "key.pem")
+ var certPEM, keyPEM []byte
+ certPEM, keyPEM, err = GenerateSelfSignedCert("test.local", []string{"test.local"})
+ require.NoError(t, err)
+ require.NoError(t, os.WriteFile(certFile, certPEM, 0o600))
+ require.NoError(t, os.WriteFile(keyFile, keyPEM, 0o600))
+
+ reloader, err = NewReloader(certFile, keyFile, nil)
+ assert.Error(t, err)
+ assert.Nil(t, reloader)
+ })
+}
+
+// TestReloaderCertificateRotation tests the certificate rotation functionality.
+func TestReloaderCertificateRotation(t *testing.T) {
+ // Test updating existing files
+ t.Run("updating existing files", func(t *testing.T) {
+ tempDir := t.TempDir()
+ certFile := filepath.Join(tempDir, "cert.pem")
+ keyFile := filepath.Join(tempDir, "key.pem")
+
+ // Create initial certificate
+ certPEM1, keyPEM1, err := GenerateSelfSignedCert("test1.local", []string{"test1.local"})
+ require.NoError(t, err)
+ require.NoError(t, os.WriteFile(certFile, certPEM1, 0o600))
+ require.NoError(t, os.WriteFile(keyFile, keyPEM1, 0o600))
+
+ log := logger.GetLogger("tls-test")
+ reloader, err := NewReloader(certFile, keyFile, log)
+ require.NoError(t, err)
+ defer reloader.Stop()
+
+ // Start reloader
+ err = reloader.Start()
+ require.NoError(t, err)
+
+ // Wait for initial certificate to be loaded
+ time.Sleep(100 * time.Millisecond)
+
+ // Verify initial certificate
+ tlsConfig := reloader.GetTLSConfig()
+ cert, err := tlsConfig.GetCertificate(nil)
+ require.NoError(t, err)
+ leafCert, err := x509.ParseCertificate(cert.Certificate[0])
+ require.NoError(t, err)
+ require.Equal(t, "test1.local", leafCert.Subject.CommonName)
+
+ // Generate and replace with new certificate files
+ certPEM2, keyPEM2, err := GenerateSelfSignedCert("test2.local", []string{"test2.local"})
+ require.NoError(t, err)
+ require.NoError(t, os.WriteFile(certFile, certPEM2, 0o600))
+ require.NoError(t, os.WriteFile(keyFile, keyPEM2, 0o600))
+
+ // Use assert.Eventually instead of time.Sleep to wait for certificate update
+ assert.Eventually(t, func() bool {
+ cert, err := tlsConfig.GetCertificate(nil)
+ if err != nil {
+ return false
+ }
+ leafCert, err := x509.ParseCertificate(cert.Certificate[0])
+ if err != nil {
+ return false
+ }
+ return leafCert.Subject.CommonName == "test2.local"
+ }, flags.EventuallyTimeout, 100*time.Millisecond)
+ })
+
+ // Test removing old files and creating new files
+ t.Run("removing and creating new files", func(t *testing.T) {
+ tempDir := t.TempDir()
+ certFile := filepath.Join(tempDir, "cert.pem")
+ keyFile := filepath.Join(tempDir, "key.pem")
+
+ // Create initial certificate
+ certPEM1, keyPEM1, err := GenerateSelfSignedCert("test1.local", []string{"test1.local"})
+ require.NoError(t, err)
+ require.NoError(t, os.WriteFile(certFile, certPEM1, 0o600))
+ require.NoError(t, os.WriteFile(keyFile, keyPEM1, 0o600))
+
+ log := logger.GetLogger("tls-test")
+ reloader, err := NewReloader(certFile, keyFile, log)
+ require.NoError(t, err)
+ defer reloader.Stop()
+
+ // Start reloader
+ err = reloader.Start()
+ require.NoError(t, err)
+
+ // Wait for initial certificate to be loaded
+ time.Sleep(100 * time.Millisecond)
+
+ // Verify initial certificate
+ tlsConfig := reloader.GetTLSConfig()
+ cert, err := tlsConfig.GetCertificate(nil)
+ require.NoError(t, err)
+ leafCert, err := x509.ParseCertificate(cert.Certificate[0])
+ require.NoError(t, err)
+ require.Equal(t, "test1.local", leafCert.Subject.CommonName)
+
+ // Remove the files
+ require.NoError(t, os.Remove(certFile))
+ require.NoError(t, os.Remove(keyFile))
+ time.Sleep(100 * time.Millisecond)
+
+ // Create new files with different content
+ certPEM2, keyPEM2, err := GenerateSelfSignedCert("test3.local", []string{"test3.local"})
+ require.NoError(t, err)
+ require.NoError(t, os.WriteFile(certFile, certPEM2, 0o600))
+ require.NoError(t, os.WriteFile(keyFile, keyPEM2, 0o600))
+
+ // Use assert.Eventually instead of time.Sleep to wait for certificate update
+ assert.Eventually(t, func() bool {
+ cert, err := tlsConfig.GetCertificate(nil)
+ if err != nil {
+ return false
+ }
+ leafCert, err := x509.ParseCertificate(cert.Certificate[0])
+ if err != nil {
+ return false
+ }
+ return leafCert.Subject.CommonName == "test3.local"
+ }, flags.EventuallyTimeout, 100*time.Millisecond)
+ })
+
+ // Test removing files without creating new ones
+ t.Run("removing files without creating new ones", func(t *testing.T) {
+ tempDir := t.TempDir()
+ certFile := filepath.Join(tempDir, "cert.pem")
+ keyFile := filepath.Join(tempDir, "key.pem")
+
+ // Create initial certificate
+ certPEM, keyPEM, err := GenerateSelfSignedCert("remove-test.local", []string{"remove-test.local"})
+ require.NoError(t, err)
+ require.NoError(t, os.WriteFile(certFile, certPEM, 0o600))
+ require.NoError(t, os.WriteFile(keyFile, keyPEM, 0o600))
+
+ log := logger.GetLogger("tls-test")
+ reloader, err := NewReloader(certFile, keyFile, log)
+ require.NoError(t, err)
+ defer reloader.Stop()
+
+ // Start reloader
+ err = reloader.Start()
+ require.NoError(t, err)
+
+ // Wait for initial certificate to be loaded
+ time.Sleep(100 * time.Millisecond)
+
+ // Get initial certificate
+ tlsConfig := reloader.GetTLSConfig()
+ cert, err := tlsConfig.GetCertificate(nil)
+ require.NoError(t, err)
+ leafCert, err := x509.ParseCertificate(cert.Certificate[0])
+ require.NoError(t, err)
+ require.Equal(t, "remove-test.local", leafCert.Subject.CommonName)
+
+ // Remove the files
+ require.NoError(t, os.Remove(certFile))
+ require.NoError(t, os.Remove(keyFile))
+
+ // Use assert.Eventually to check certificate is still available
+ assert.Eventually(t, func() bool {
+ cert, err := tlsConfig.GetCertificate(nil)
+ if err != nil {
+ return false
+ }
+ leafCert, err := x509.ParseCertificate(cert.Certificate[0])
+ if err != nil {
+ return false
+ }
+ return leafCert.Subject.CommonName == "remove-test.local"
+ }, flags.EventuallyTimeout, 100*time.Millisecond)
+ })
+}
+
+// TestReloaderInvalidCertificate tests handling of invalid certificates.
+func TestReloaderInvalidCertificate(t *testing.T) {
+ tempDir := t.TempDir()
+ certFile := filepath.Join(tempDir, "cert.pem")
+ keyFile := filepath.Join(tempDir, "key.pem")
+
+ // Create valid initial files
+ certPEM, keyPEM, err := GenerateSelfSignedCert("initial.local", []string{"initial.local"})
+ require.NoError(t, err)
+ require.NoError(t, os.WriteFile(certFile, certPEM, 0o600))
+ require.NoError(t, os.WriteFile(keyFile, keyPEM, 0o600))
+
+ log := logger.GetLogger("tls-test")
+ reloader, err := NewReloader(certFile, keyFile, log)
+ require.NoError(t, err)
+ require.NoError(t, reloader.Start())
+ defer reloader.Stop()
+
+ // Wait for initial certificate to be loaded
+ time.Sleep(100 * time.Millisecond)
+
+ // Initial verification
+ tlsConfig := reloader.GetTLSConfig()
+ cert, err := tlsConfig.GetCertificate(nil)
+ require.NoError(t, err)
+ leafCert, err := x509.ParseCertificate(cert.Certificate[0])
+ require.NoError(t, err)
+ require.Equal(t, "initial.local", leafCert.Subject.CommonName)
+
+ // Create invalid certificate and key files
+ require.NoError(t, os.WriteFile(certFile, []byte("invalid cert"), 0o600))
+ require.NoError(t, os.WriteFile(keyFile, []byte("invalid key"), 0o600))
+
+ // Use assert.Eventually to verify still using the last valid certificate
+ assert.Eventually(t, func() bool {
+ cert, certErr := tlsConfig.GetCertificate(nil)
+ if certErr != nil {
+ return false
+ }
+ leafCert, leafErr := x509.ParseCertificate(cert.Certificate[0])
+ if leafErr != nil {
+ return false
+ }
+ return leafCert.Subject.CommonName == "initial.local"
+ }, flags.EventuallyTimeout, 100*time.Millisecond)
+
+ // Create valid files after invalid ones
+ certPEM2, keyPEM2, err := GenerateSelfSignedCert("recovered.local", []string{"recovered.local"})
+ require.NoError(t, err)
+ require.NoError(t, os.WriteFile(certFile, certPEM2, 0o600))
+ require.NoError(t, os.WriteFile(keyFile, keyPEM2, 0o600))
+
+ // Use assert.Eventually to verify certificate has been updated
+ assert.Eventually(t, func() bool {
+ cert, certErr := tlsConfig.GetCertificate(nil)
+ if certErr != nil {
+ return false
+ }
+ leafCert, leafErr := x509.ParseCertificate(cert.Certificate[0])
+ if leafErr != nil {
+ return false
+ }
+ return leafCert.Subject.CommonName == "recovered.local"
+ }, flags.EventuallyTimeout, 100*time.Millisecond)
+}
+
+// TestReloaderTLSConfig tests TLS configuration generation.
+func TestReloaderTLSConfig(t *testing.T) {
+ tempDir := t.TempDir()
+ certFile := filepath.Join(tempDir, "cert.pem")
+ keyFile := filepath.Join(tempDir, "key.pem")
+
+ // Create valid files
+ certPEM, keyPEM, err := GenerateSelfSignedCert("config.test.local", []string{"config.test.local"})
+ require.NoError(t, err)
+ require.NoError(t, os.WriteFile(certFile, certPEM, 0o600))
+ require.NoError(t, os.WriteFile(keyFile, keyPEM, 0o600))
+
+ log := logger.GetLogger("tls-test")
+ reloader, err := NewReloader(certFile, keyFile, log)
+ require.NoError(t, err)
+
+ // Test TLS Config
+ tlsConfig := reloader.GetTLSConfig()
+ assert.NotNil(t, tlsConfig.GetCertificate)
+ assert.Equal(t, uint16(tls.VersionTLS12), tlsConfig.MinVersion)
+ assert.Equal(t, []string{"h2"}, tlsConfig.NextProtos)
+
+ // Test gRPC Transport Credentials
+ creds := credentials.NewTLS(tlsConfig)
+ assert.NotNil(t, creds)
+ info := creds.Info()
+ assert.Equal(t, "tls", info.SecurityProtocol)
+}
+
+// TestClientCertReloader tests the client certificate reloader functionality.
+func TestClientCertReloader(t *testing.T) {
+ tempDir := t.TempDir()
+ certFile := filepath.Join(tempDir, "cert.pem")
+
+ // Create a self-signed CA certificate
+ certPEM, _, err := GenerateSelfSignedCert("ca.test.local", []string{"ca.test.local"})
+ require.NoError(t, err)
+ require.NoError(t, os.WriteFile(certFile, certPEM, 0o600))
+
+ log := logger.GetLogger("tls-test")
+
+ // Test basic initialization
+ t.Run("initialization", func(t *testing.T) {
+ reloader, err := NewClientCertReloader(certFile, log)
+ require.NoError(t, err)
+ require.NotNil(t, reloader)
+
+ // Start the reloader
+ require.NoError(t, reloader.Start())
+ defer reloader.Stop()
+
+ // Test GetClientTLSConfig
+ clientConfig, err := reloader.GetClientTLSConfig("server.example.com")
+ require.NoError(t, err)
+ assert.NotNil(t, clientConfig.RootCAs)
+ assert.Equal(t, "server.example.com", clientConfig.ServerName)
+ assert.Equal(t, uint16(tls.VersionTLS12), clientConfig.MinVersion)
+ })
+
+ // Test certificate updates
+ t.Run("certificate updates", func(t *testing.T) {
+ reloader, err := NewClientCertReloader(certFile, log)
+ require.NoError(t, err)
+ require.NoError(t, reloader.Start())
+ defer reloader.Stop()
+
+ // Get update channel
+ updateCh := reloader.GetUpdateChannel()
+
+ // Create a channel to notify when update is received
+ updateReceived := make(chan struct{})
+ go func() {
+ <-updateCh
+ close(updateReceived)
+ }()
+
+ // Allow time for watcher to be fully established
+ time.Sleep(100 * time.Millisecond)
+
+ // Replace the certificate
+ certPEM2, _, err := GenerateSelfSignedCert("updated-ca.test.local", []string{"updated-ca.test.local"})
+ require.NoError(t, err)
+ require.NoError(t, os.WriteFile(certFile, certPEM2, 0o600))
+
+ // Verify notification is received
+ select {
+ case <-updateReceived:
+ // Notification received
+ case <-time.After(flags.EventuallyTimeout):
+ assert.Fail(t, "Timed out waiting for certificate update notification")
+ }
+
+ // Verify client gets new config
+ updatedConfig, err := reloader.GetClientTLSConfig("server.example.com")
+ require.NoError(t, err)
+ assert.NotNil(t, updatedConfig.RootCAs)
+
+ // Verify TLS config works correctly with the server name
+ assert.Equal(t, "server.example.com", updatedConfig.ServerName)
+ })
+
+ // Test error conditions
+ t.Run("error cases", func(t *testing.T) {
+ // Empty path
+ _, err := NewClientCertReloader("", log)
+ assert.Error(t, err)
+
+ // Invalid file content
+ invalidCertFile := filepath.Join(tempDir, "invalid.pem")
+ require.NoError(t, os.WriteFile(invalidCertFile, []byte("invalid certificate"), 0o600))
+ _, err = NewClientCertReloader(invalidCertFile, log)
+ assert.Error(t, err)
+
+ // Nil logger
+ _, err = NewClientCertReloader(certFile, nil)
+ assert.Error(t, err)
+ })
+
+ // Test removing and recreating certificate file
+ t.Run("remove and recreate certificate", func(t *testing.T) {
+ reloader, err := NewClientCertReloader(certFile, log)
+ require.NoError(t, err)
+ require.NoError(t, reloader.Start())
+ defer reloader.Stop()
+
+ // Get initial client config
+ initialConfig, err := reloader.GetClientTLSConfig("server.example.com")
+ require.NoError(t, err)
+ assert.NotNil(t, initialConfig.RootCAs)
+
+ // Get update channel
+ updateCh := reloader.GetUpdateChannel()
+ updateReceived := make(chan struct{})
+ go func() {
+ <-updateCh
+ close(updateReceived)
+ }()
+
+ // Allow time for watcher to be fully established
+ time.Sleep(100 * time.Millisecond)
+
+ // Remove certificate file
+ require.NoError(t, os.Remove(certFile))
+
+ // Wait a moment
+ time.Sleep(100 * time.Millisecond)
+
+ // Create a new certificate file
+ certPEM3, _, err := GenerateSelfSignedCert("recreated-ca.test.local", []string{"recreated-ca.test.local"})
+ require.NoError(t, err)
+ require.NoError(t, os.WriteFile(certFile, certPEM3, 0o600))
+
+ // Verify update is received
+ select {
+ case <-updateReceived:
+ // Notification received
+ case <-time.After(flags.EventuallyTimeout):
+ assert.Fail(t, "Timed out waiting for certificate update notification after recreation")
+ }
+
+ // Verify config works with new certificate
+ time.Sleep(100 * time.Millisecond) // Give time for reloader to update
+ assert.Eventually(t, func() bool {
+ newConfig, err := reloader.GetClientTLSConfig("server.example.com")
+ return err == nil && newConfig.RootCAs != nil
+ }, flags.EventuallyTimeout, 100*time.Millisecond)
+ })
+}
diff --git a/test/integration/standalone/other/tls_test.go b/test/integration/standalone/other/tls_test.go
index 8d4d5df1..2af9334c 100644
--- a/test/integration/standalone/other/tls_test.go
+++ b/test/integration/standalone/other/tls_test.go
@@ -18,6 +18,12 @@
package integration_other_test
import (
+ cryptotls "crypto/tls"
+ "crypto/x509"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
"path/filepath"
"runtime"
"time"
@@ -33,6 +39,7 @@ import (
"github.com/apache/skywalking-banyandb/pkg/test/helpers"
"github.com/apache/skywalking-banyandb/pkg/test/setup"
"github.com/apache/skywalking-banyandb/pkg/timestamp"
+ "github.com/apache/skywalking-banyandb/pkg/tls"
casesMeasureData "github.com/apache/skywalking-banyandb/test/cases/measure/data"
)
@@ -42,13 +49,14 @@ var _ = g.Describe("Query service_cpm_minute", func() {
var interval time.Duration
var conn *grpclib.ClientConn
var goods []gleak.Goroutine
+ var addr string
+ var certFile, keyFile string
g.BeforeEach(func() {
_, currentFile, _, _ := runtime.Caller(0)
basePath := filepath.Dir(currentFile)
- certFile := filepath.Join(basePath, "testdata/server_cert.pem")
- keyFile := filepath.Join(basePath, "testdata/server_key.pem")
- var addr string
+ certFile = filepath.Join(basePath, "testdata/server_cert.pem")
+ keyFile = filepath.Join(basePath, "testdata/server_key.pem")
addr, _, deferFn = setup.StandaloneWithTLS(certFile, keyFile)
var err error
creds, err := credentials.NewClientTLSFromFile(certFile, "localhost")
@@ -74,4 +82,150 @@ var _ = g.Describe("Query service_cpm_minute", func() {
}, helpers.Args{Input: "all", Duration: 25 * time.Minute, Offset: -20 * time.Minute})
}, flags.EventuallyTimeout).Should(gm.Succeed())
})
+
+ // This comprehensive test verifies that both HTTP and gRPC connections
+ // correctly handle certificate updates. It ensures that:
+ // 1. The server properly detects when certificate files change
+ // 2. Existing connections are properly terminated
+ // 3. New connections use the updated certificates
+ // This test covers both HTTP and gRPC certificate update scenarios.
+ g.It("queries an updated TLS server with both gRPC and HTTP", func() {
+ // Create a temporary directory for certificate files
+ tempDir, err := os.MkdirTemp("", "tls-test-*")
+ gm.Expect(err).NotTo(gm.HaveOccurred())
+ defer os.RemoveAll(tempDir)
+
+ // Copy the original certificate and key to the temporary directory
+ tempCertFile := filepath.Join(tempDir, "cert.pem")
+ tempKeyFile := filepath.Join(tempDir, "key.pem")
+
+ // Read original certificate and key
+ originalCert, err := os.ReadFile(certFile)
+ gm.Expect(err).NotTo(gm.HaveOccurred())
+ originalKey, err := os.ReadFile(keyFile)
+ gm.Expect(err).NotTo(gm.HaveOccurred())
+
+ // Write to temporary location
+ err = os.WriteFile(tempCertFile, originalCert, 0o600)
+ gm.Expect(err).NotTo(gm.HaveOccurred())
+ err = os.WriteFile(tempKeyFile, originalKey, 0o600)
+ gm.Expect(err).NotTo(gm.HaveOccurred())
+
+ // Start a new server using the temporary certificate files
+ grpcAddr, httpAddr, tempDeferFn := setup.StandaloneWithTLS(tempCertFile, tempKeyFile)
+ defer tempDeferFn()
+
+ // Create a secure HTTP client with the initial certificates
+ httpClient := &http.Client{
+ Transport: &http.Transport{
+ TLSClientConfig: &cryptotls.Config{
+ InsecureSkipVerify: false,
+ RootCAs: x509.NewCertPool(),
+ MinVersion: cryptotls.VersionTLS12,
+ },
+ },
+ }
+ // Add the cert to the pool
+ certPool := httpClient.Transport.(*http.Transport).TLSClientConfig.RootCAs
+ certPool.AppendCertsFromPEM(originalCert)
+
+ // Verify HTTP server is working with original certificates
+ groupListURL := fmt.Sprintf("https://%s/api/v1/group/schema/lists", httpAddr)
+ gm.Eventually(func() error {
+ var respErr error
+ resp, respErr := httpClient.Get(groupListURL)
+ if respErr != nil {
+ return respErr
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
+ }
+ return nil
+ }, flags.EventuallyTimeout).Should(gm.Succeed())
+
+ // Create initial gRPC connection with the original certificate
+ creds, err := credentials.NewClientTLSFromFile(tempCertFile, "localhost")
+ gm.Expect(err).NotTo(gm.HaveOccurred())
+ grpcConn, err := grpchelper.Conn(grpcAddr, 10*time.Second, grpclib.WithTransportCredentials(creds))
+ gm.Expect(err).NotTo(gm.HaveOccurred())
+ defer grpcConn.Close()
+
+ // Populate test data and verify with original certificate connection first
+ ns := timestamp.NowMilli().UnixNano()
+ testBaseTime := time.Unix(0, ns-ns%int64(time.Minute))
+ casesMeasureData.Write(grpcConn, "service_cpm_minute", "sw_metric", "service_cpm_minute_data.json", testBaseTime, interval)
+
+ // Verify using the initial connection before updating certificates
+ gm.Eventually(func(innerGm gm.Gomega) {
+ casesMeasureData.VerifyFn(innerGm, helpers.SharedContext{
+ Connection: grpcConn,
+ BaseTime: testBaseTime,
+ }, helpers.Args{Input: "all", Duration: 25 * time.Minute, Offset: -20 * time.Minute})
+ }, flags.EventuallyTimeout).Should(gm.Succeed())
+
+ // Generate a new certificate with a different CommonName
+ certPEM, keyPEM, err := tls.GenerateSelfSignedCert("updated-localhost", []string{"localhost"})
+ gm.Expect(err).NotTo(gm.HaveOccurred())
+
+ // Update the certificate files in the temporary location
+ err = os.WriteFile(tempCertFile, certPEM, 0o600)
+ gm.Expect(err).NotTo(gm.HaveOccurred())
+ err = os.WriteFile(tempKeyFile, keyPEM, 0o600)
+ gm.Expect(err).NotTo(gm.HaveOccurred())
+
+ // Wait for the server to reload the certificates
+ time.Sleep(1 * time.Second)
+
+ // Create a new HTTP client with updated certificates
+ newHTTPClient := &http.Client{
+ Transport: &http.Transport{
+ TLSClientConfig: &cryptotls.Config{
+ InsecureSkipVerify: false,
+ RootCAs: x509.NewCertPool(),
+ MinVersion: cryptotls.VersionTLS12,
+ },
+ },
+ }
+ // Add the new cert to the pool
+ newCertPool := newHTTPClient.Transport.(*http.Transport).TLSClientConfig.RootCAs
+ newCertPool.AppendCertsFromPEM(certPEM)
+
+ // Verify HTTP server works with the new certificates
+ gm.Eventually(func() error {
+ var respErr2 error
+ resp, respErr2 := newHTTPClient.Get(groupListURL)
+ if respErr2 != nil {
+ return respErr2
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
+ }
+ // Read and verify the response body
+ body, readErr := io.ReadAll(resp.Body)
+ if readErr != nil {
+ return fmt.Errorf("failed to read response body: %w", readErr)
+ }
+ if len(body) == 0 {
+ return fmt.Errorf("empty response body")
+ }
+ return nil
+ }, flags.EventuallyTimeout).Should(gm.Succeed())
+
+ // Create a new gRPC connection with updated certificates
+ newCreds, err := credentials.NewClientTLSFromFile(tempCertFile, "updated-localhost")
+ gm.Expect(err).NotTo(gm.HaveOccurred())
+ newGrpcConn, err := grpchelper.Conn(grpcAddr, 10*time.Second, grpclib.WithTransportCredentials(newCreds))
+ gm.Expect(err).NotTo(gm.HaveOccurred())
+ defer newGrpcConn.Close()
+
+ // Verify data access works through a new connection
+ gm.Eventually(func(innerGm gm.Gomega) {
+ casesMeasureData.VerifyFn(innerGm, helpers.SharedContext{
+ Connection: newGrpcConn,
+ BaseTime: testBaseTime,
+ }, helpers.Args{Input: "all", Duration: 25 * time.Minute, Offset: -20 * time.Minute})
+ }, flags.EventuallyTimeout).Should(gm.Succeed())
+ })
})