Skip to content

Commit

Permalink
Add support for TLS configuration for NATS
Browse files Browse the repository at this point in the history
  • Loading branch information
arnarg committed Jul 27, 2023
1 parent ceea34f commit 8116e8f
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
3 changes: 3 additions & 0 deletions cfg/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ type NATSConfiguration struct {
SeedFile string `toml:"seed_file"`
CredsUser string `toml:"user_name"`
CredsPassword string `toml:"user_password"`
CAFile string `toml:"ca_file"`
CertFile string `toml:"cert_file"`
KeyFile string `toml:"key_file"`
BindAddress string `toml:"bind_address"`
}

Expand Down
18 changes: 18 additions & 0 deletions logstream/replicator.go
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,24 @@ func (r *Replicator) ForceSaveSnapshot() {
r.lastSnapshot = time.Now()
}

func (r *Replicator) ReloadCertificates() error {
if cfg.Config.NATS.CAFile != "" {
err := nats.RootCAs(cfg.Config.NATS.CAFile)(&r.client.Opts)
if err != nil {
return err
}
}

if cfg.Config.NATS.CertFile != "" && cfg.Config.NATS.KeyFile != "" {
err := nats.ClientCert(cfg.Config.NATS.CertFile, cfg.Config.NATS.KeyFile)(&r.client.Opts)
if err != nil {
return err
}
}

return nil
}

func (r *Replicator) invokeListener(callback func(payload []byte) error, msg *nats.Msg) error {
var err error
payload := msg.Data
Expand Down
22 changes: 22 additions & 0 deletions stream/nats.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,13 @@ func Connect() (*nats.Conn, error) {
return nil, err
}

tls, err := getNatsTLSFromConfig()
if err != nil {
return nil, err
}

opts = append(opts, creds...)
opts = append(opts, tls...)
if len(cfg.Config.NATS.URLs) == 0 {
embedded, err := startEmbeddedServer(cfg.Config.NodeName())
if err != nil {
Expand Down Expand Up @@ -54,3 +60,19 @@ func getNatsAuthFromConfig() ([]nats.Option, error) {

return opts, nil
}

func getNatsTLSFromConfig() ([]nats.Option, error) {
opts := make([]nats.Option, 0)

if cfg.Config.NATS.CAFile != "" {
opt := nats.RootCAs(cfg.Config.NATS.CAFile)
opts = append(opts, opt)
}

if cfg.Config.NATS.CertFile != "" && cfg.Config.NATS.KeyFile != "" {
opt := nats.ClientCert(cfg.Config.NATS.CertFile, cfg.Config.NATS.KeyFile)
opts = append(opts, opt)
}

return opts, nil
}

0 comments on commit 8116e8f

Please sign in to comment.