MCPcopy
hub / github.com/nats-io/nats.go / TestClientTLSConfig

Function TestClientTLSConfig

test/conn_test.go:239–340  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

237}
238
239func TestClientTLSConfig(t *testing.T) {
240 s, opts := RunServerWithConfig("./configs/tlsverify.conf")
241 defer s.Shutdown()
242
243 endpoint := fmt.Sprintf("%s:%d", opts.Host, opts.Port)
244 secureURL := fmt.Sprintf("nats://%s", endpoint)
245
246 // Make sure this fails
247 nc, err := nats.Connect(secureURL, nats.Secure())
248 if err == nil {
249 nc.Close()
250 t.Fatal("Should have failed (TLS) connection without client certificate")
251 }
252 cert, err := os.ReadFile("./configs/certs/client-cert.pem")
253 if err != nil {
254 t.Fatal("Failed to read client certificate")
255 }
256 key, err := os.ReadFile("./configs/certs/client-key.pem")
257 if err != nil {
258 t.Fatal("Failed to read client key")
259 }
260 rootCAs, err := os.ReadFile("./configs/certs/ca.pem")
261 if err != nil {
262 t.Fatal("Failed to read root CAs")
263 }
264
265 certCB := func() (tls.Certificate, error) {
266 cert, err := tls.X509KeyPair(cert, key)
267 if err != nil {
268 return tls.Certificate{}, fmt.Errorf("nats: error loading client certificate: %w", err)
269 }
270 cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
271 if err != nil {
272 return tls.Certificate{}, fmt.Errorf("nats: error parsing client certificate: %w", err)
273 }
274 return cert, nil
275 }
276
277 caCB := func() (*x509.CertPool, error) {
278 pool := x509.NewCertPool()
279 ok := pool.AppendCertsFromPEM(rootCAs)
280 if !ok {
281 return nil, errors.New("nats: failed to parse root certificate from")
282 }
283 return pool, nil
284 }
285
286 // Check parameters validity
287 _, err = nats.Connect(secureURL, nats.ClientTLSConfig(nil, nil))
288 if !errors.Is(err, nats.ErrClientCertOrRootCAsRequired) {
289 t.Fatalf("Expected error %q, got %q", nats.ErrClientCertOrRootCAsRequired, err)
290 }
291
292 certErr := &tls.CertificateVerificationError{}
293 // Should fail because of missing CA
294 _, err = nats.Connect(secureURL,
295 nats.ClientCert("./configs/certs/client-cert.pem", "./configs/certs/client-key.pem"))
296 if ok := errors.As(err, &certErr); !ok {

Callers

nothing calls this directly

Calls 12

ConnectMethod · 0.80
ErrorfMethod · 0.80
FatalfMethod · 0.80
EqualMethod · 0.80
RunServerWithConfigFunction · 0.70
WaitFunction · 0.70
ErrorMethod · 0.65
SubscribeMethod · 0.65
PublishMethod · 0.65
CloseMethod · 0.45
IsMethod · 0.45
FlushMethod · 0.45

Tested by

no test coverage detected