Skip to content

Commit

Permalink
feat(tls): introduce tls direct passing instead of using files
Browse files Browse the repository at this point in the history
  • Loading branch information
AlanLonguet committed Nov 18, 2022
1 parent 1b402d1 commit 4545163
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ type conf struct {
clientCertPath string
// path to client cert key file
clientCertKeyPath string
// ca certificate as a string
ca string
// client certificate as a string
clientCert string
// client certificate key as a string
clientKey string
}

//nolint:nosnakecase // their choice not mine
Expand Down Expand Up @@ -112,6 +118,21 @@ func (m *MqttAPI) client(c goja.ConstructorCall) *goja.Object {
} else {
clientConf.clientCertKeyPath = clientCertKeyPathValue.String()
}
if ca := c.Argument(9); ca == nil || goja.IsUndefined(ca) {
clientConf.ca = ""
} else {
clientConf.ca = ca.String()
}
if clientCert := c.Argument(10); clientCert == nil || goja.IsUndefined(clientCert) {
clientConf.clientCert = ""
} else {
clientConf.clientCert = clientCert.String()
}
if clientKey := c.Argument(11); clientKey == nil || goja.IsUndefined(clientKey) {
clientConf.clientKey = ""
} else {
clientConf.clientKey = clientKey.String()
}

client := &client{
vu: m.vu,
Expand Down Expand Up @@ -165,6 +186,16 @@ func (c *client) Connect() error {
RootCAs: rootCA,
MinVersion: tls.VersionTLS12,
}
} else if len(c.conf.ca) > 0 {
rootCA := x509.NewCertPool()
loadCA := rootCA.AppendCertsFromPEM([]byte(c.conf.ca))
if !loadCA {
panic("failed to parse root certificate")
}
tlsConfig = &tls.Config{
RootCAs: rootCA,
MinVersion: tls.VersionTLS12,
}
}
// Use local cert if specified
if len(c.conf.clientCertPath) > 0 {
Expand All @@ -180,6 +211,19 @@ func (c *client) Connect() error {
MinVersion: tls.VersionTLS12,
}
}
} else if len(c.conf.clientCert) > 0 && len(c.conf.clientKey) > 0 {
cert, err := tls.X509KeyPair([]byte(c.conf.clientCert), []byte(c.conf.clientKey))
if err != nil {
panic("failed to parse client certificate")
}
if tlsConfig != nil {
tlsConfig.Certificates = []tls.Certificate{cert}
} else {
tlsConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
MinVersion: tls.VersionTLS12,
}
}
}
if tlsConfig != nil {
opts.SetTLSConfig(tlsConfig)
Expand Down

0 comments on commit 4545163

Please # to comment.