(t *testing.T)
| 237 | } |
| 238 | |
| 239 | func 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 { |
nothing calls this directly
no test coverage detected