How the client decides whether a connection uses TLS, which SSLContext it uses, what opentls does and does not do, how the server's name is checked against its certificate, and the rule for server lists that mix schemes. This is the detail behind the SSLContext and Connection Security sections of the README.
A connection has one SSLContext. It is used for every server the connection ever talks to: the bootstrap servers given in the options and the servers discovered from the cluster through connect_urls. A discovered server takes the scheme of the server that reported it, so it is dialed with that server's transport and, the context being per connection, with the same TLS and the same context; section 10 has the form of a connect_urls entry.
The context is accepted or created once, when Options.Builder.build() runs, in this order. The first rule that applies wins and the rest are not consulted.
sslContext(SSLContext ctx)was called: that context, as given.sslContextFactory(SSLContextFactory)was set, or theio.nats.client.ssl.context.factory.classproperty named a class: the factory builds the context from the keystore, truststore and algorithm properties.keystoreortruststorewas set, by builder or property: the client builds a context from those JKS files with thetls.algorithmproperty,SunX509by default.opentls()was called, theio.nats.client.opentlsproperty is true, or any bootstrap server has theopentls://scheme: the trust-all context described in section 3.secure()ortlsFirst()was called, theio.nats.client.secureproperty is true, or any bootstrap server has thetls://orwss://scheme:SSLContext.getDefault(), described in section 2.- Otherwise no context, and the connection is plain TCP. A server that requires TLS then fails the attempt with "SSL required by server."; section 8 says when that closes the connection.
Rules 4 and 5 look at the bootstrap servers only when neither opentls nor secure was set explicitly. Asking for both is an error, section 5.
When the options end up with a context, by any of rules 1 to 5, a ws:// server in the list is an error at build(): ws:// is a plain websocket and is never upgraded to TLS, so that server would be reached without it. Use wss:// for it. A nats:// server is allowed, because it is upgraded to TLS like every other server of the connection. A connect_urls entry never names the transport: an entry that carries a scheme, ws:// or any other, is skipped before it reaches the pool, section 10. A ws:// server supplied by a custom ServerPool is never dialed: when the pool hands it out, the connection skips it and goes on to the next server, reports it through ErrorListener.serverRejected, and tells the pool through ServerPool.serverRejected, so the default pool drops it and does not take it back.
SSLContext.getDefault() is the JVM's default: it verifies the server's certificate chain against the JVM trust store, cacerts in the JDK's lib/security, or whatever the javax.net.ssl.trustStore system properties point at. It presents the client certificate from javax.net.ssl.keyStore when a server asks for one. It does not read the operating system's certificate store; a CA installed in Windows or macOS is not trusted by the JVM unless it is also in the JVM trust store or the JVM is configured to use the system store.
So tls:// works out of the box against a server whose certificate chains to a public CA, and against a private CA once that CA is in the JVM trust store or supplied through the truststore properties, an SSLContextFactory, or an SSLContext you build. tlsFirst() (section 7) and tlsServerName(name) (section 4) select the default context as well when nothing else has chosen one.
The contexts the client builds itself, from the keystore and truststore properties and for opentls, are created for TLS, the highest version the JVM supports, so they offer TLS 1.3 where the JVM has it; the default context is the JVM's own. On every connection, whatever the context, the client enables TLS 1.2 and above only: it never negotiates TLS 1.0 or 1.1 and never falls back below TLS 1.2, as RFC 8996 requires. nats-server never negotiates below TLS 1.2 either.
opentls builds a context whose trust manager accepts any server certificate chain: self-signed, expired, revoked, issued by anyone, for any name. It presents no client certificate, so the server must have client verification off for it to connect.
The same context can be supplied by hand, and the client treats it identically: sslContext(SSLUtils.createTrustAllTlsContext()), sslContext(SSLUtils.createOpenTLSContext()), or any SSLContext initialized with a trust manager whose checkServerTrusted does not throw. opentls without a context and a hand-supplied trust-all context are the same thing. Nothing in the client detects a trust-all context, warns about it, or treats it differently from one that verifies.
TLS gives two things: encryption of the bytes, and proof of who is at the other end. The second comes entirely from checking the server's certificate against something the client already trusts. A trust-all context keeps the encryption and discards the proof. The connection is encrypted to whoever answered.
With a trust-all context, anything on the network path that can answer the TCP connection can present its own certificate and the client completes the handshake with it: a compromised router or host on the same network, a wrongly configured proxy or load balancer, a DNS answer that points at the wrong machine, a container or pod that took over an address. The client then sends its CONNECT with the credentials the options hold.
- A username and password, or a token, are sent inside the TLS session and are captured outright.
- NKey and credentials-file authentication sign a nonce the server sends. An impersonator that relays to the real server passes the real nonce through and forwards the signature, so it authenticates to the real server as the client. Signed authentication does not prevent this; only server verification does.
- From then on the impersonator reads every message the client publishes, delivers any message it likes to the client's subscriptions, and can relay everything to the real server so that nothing looks wrong to either side.
The client cannot notice. The handshake succeeded, the connection reports as secure, and no error, event or log line says that the certificate was not checked. This is the same for the equivalent switch in every other client, which is why Go's documentation says InsecureSkipVerify "should NOT be used in a production setting".
Separately from the chain check, the client checks the server's name against the certificate, section 4, and does so under a trust-all context too. That check only proves that the certificate names the host, and with a trust-all context anyone can present a certificate that names the host, so it does not restore the proof the chain check gave. With tlsVerifyHostname(false) as well, no property of the certificate is tested at all.
opentls and a hand-supplied trust-all context are for development and tests, where the server is on the developer's own machine or the certificate is known to be throwaway. Outside that, do not use either. For a server with a private CA, put the CA in the JVM trust store, or in a truststore given to the client through the truststore properties, or build an SSLContext from it; sections 2 and 6. The effort is one keytool import, and the connection then proves who it is talking to.
opentls is never selected unless asked for, by one of three routes: the opentls() builder method, the io.nats.client.opentls=true property, or an opentls:// scheme on a bootstrap server. The third route means a configuration value alone can select it; review server URLs that come from configuration with that in mind. A hand-supplied context is selected by sslContext(ctx) and is used whatever the flags and schemes say.
Because the context is per connection, either form applies to every server the connection reaches, including discovered ones.
After the chain check, the client checks that the certificate is issued for the server name the connection was made with. The check is the one the JDK performs for HTTPS: the name is matched against the certificate's subject alternative names, a DNS entry for a hostname, an ip address entry for an ip literal. It is on by default and applies under every context, including the trust-all context of section 3.
The name checked is the hostname in the server url, in every HostnameResolveMode, including the modes that resolve the hostname to ip addresses before connecting. The same name is sent as the TLS server name (SNI), so a server or proxy that selects its certificate by name selects the right one. A server given by ip address in the url is checked as an ip address, so its certificate must carry that address as a subject alternative name. A server discovered from connect_urls as a bare ip address is checked against the hostname it inherits from the server that reported it, over any number of hops: the hostname that server was configured with, or the one it inherited itself, and that name is sent as SNI. A discovered ip address with no name to inherit, learned through a server configured by ip address, is not connected to over TLS: the entry is skipped and reported through ErrorListener.discoveredServerSkipped, with a reason that names the two settings that allow it. tlsServerName, below, gives every server one name. tlsVerifyDiscoveredByIp() on the builder, or the io.nats.client.tls.verify.discovered.by.ip property, verifies a discovered ip address against its address instead of an inherited name, with no SNI, and lets the client connect to one that has no name; it is for clusters whose node certificates carry only ip addresses, and safe only where the CA that issued them is not shared with others. It has no effect while a TLS server name is set, and neither it nor the skip applies with the name check turned off. Before this rule a discovered ip address with no name was verified against its address, which is what the option does: a deployment that connects by ip address to a cluster that advertises ip addresses, with certificates that carry those addresses, now needs the option.
tlsServerName(name) on the builder, or the io.nats.client.tls.server.name property, sets one name for every server, configured or discovered: it is verified against and sent as SNI in place of each server's own name and of the name a discovered ip address inherits. It is the first remedy when certificates do not carry the name in the url: servers reached by ip address, or through a load balancer, proxy or service name, whose certificates all carry one name. A TLS server name asks for TLS: set with no other TLS setting, it selects the default context of section 2. One trailing dot is stripped from every name verified against or sent as SNI, so tls://nats.example.com.:4222 is dialed as written and verified as nats.example.com; a name that is an ip address, in the url or as the TLS server name, is verified as an ip address and no SNI is sent.
The check is performed by the trust manager in use. The JDK performs it for its own trust managers, which the default context and a context built from a keystore and truststore have, and for any plain X509TrustManager, which it wraps; the trust-all manager of opentls is one of those. A custom X509ExtendedTrustManager is responsible for its own identity check, so a context built with one is only checked if the manager does it.
A connection to a server whose certificate does not name it fails with an SSLHandshakeException that states the name the client expected and where it came from: the host of the url, the TLS server name, or the server that reported a discovered ip address. The JDK's CertificateException is its cause; the JDK does not expose the names the certificate carries, so the error cannot state them. The initial connect's IOException carries the last attempt's failure as its cause. The remedies, in this order: set tlsServerName to a name the certificate carries, reissue the certificate for the name, connect by a name the certificate carries, or, for a server discovered from the cluster, have it advertise a name its certificate carries (client_advertise on nats-server). tlsVerifyHostname(false) on the builder, or the io.nats.client.tls.verify.hostname=false property, turns the check off as the last resort; that removes the proof that the server is the one named in the url, section 3, so keep it for development against a certificate that is known not to name the server.
Options that ask for the default context and the trust-all context at the same time are rejected when they are built, with IllegalStateException:
Options ask for both the default SSL context (secure, or a tls or wss server url) and the trust-all SSL context (opentls, or an opentls server url). One SSL context serves every server, so a connection cannot both verify certificates and trust all of them. Choose one, or provide an SSLContext.
That covers secure() together with opentls(), the secure and opentls properties both true, and a bootstrap list that contains both an opentls:// server and a tls:// or wss:// server. The reason is section 1: one context serves every server, so a connection cannot both verify certificates and trust all of them, and letting opentls win, which is what happened before this rule, silently removed the verification the other side asked for.
One explicit choice is not a conflict: opentls() with tls:// servers builds the trust-all context, secure() with opentls:// servers builds the default context, because an explicit flag stops the schemes from being consulted, and a context given with sslContext(ctx) is used whatever the flags and schemes are. Plain nats:// servers may be mixed with either secure scheme, as before.
To fix rejected options, choose one of the two, or supply the context you want with sslContext(ctx).
A server configured with verify: true requires a client certificate. Supply it through the keystore and keystorePassword properties together with truststore and truststorePassword, through an SSLContextFactory, through an SSLContext built with key managers, or through the javax.net.ssl.keyStore system properties when using the default context. opentls presents no client certificate and cannot be used against such a server.
The README's TLS Certs section shows how the test keystore and truststore are produced from the PEM files in src/test/resources/certs.
tlsFirst() performs the TLS handshake before reading the server's INFO, for servers configured with handshake_first. It asks for TLS: when rules 1 to 4 of section 1 give no context, it selects SSLContext.getDefault(), rule 5.
Whether the client attempts the TLS upgrade is decided by whether it has a context; whether the server requires or offers TLS comes from its INFO. The README's "TLS client versus server checks" table lists the six combinations and the two that fail with an IOException. Either mismatch fails the attempt and the next server is tried, since a single server can be misconfigured. When every server of one full round over the server list fails with the mismatch, retrying cannot help, because the same options are used for every server, and the connection is closed: the initial connect throws, also with reconnect-on-connect, and a reconnect ends with the connection closed. A server that cannot be reached is not a mismatch, so a round that contains one is not conclusive and the normal reconnect rules apply. The scheme of a url that a custom ServerPool hands out does not change which servers the client uses TLS with; only the options decide.
With TLS after INFO, the usual flow for tls:// and secure(), the server's first INFO arrives in plaintext before the handshake. The client takes its nonce, limits, version and TLS flags for that attempt, and nothing else: its connect_urls are not added to the server list and its lame duck flag raises no event, whether the handshake then succeeds or fails. Discovered servers come from the INFOs received inside TLS. nats-server 2.12 and later answer the client's first PING with PONG followed by such an INFO, and the client waits for it before it reports connected, for at most the connection timeout, on a timer of its own; when it arrives later it is applied then. Before 2.12 the server sends an INFO inside TLS only when the cluster's addresses change, so a connection to an older cluster has no discovered servers until that happens. To have failover servers from the start against such a cluster, configure more than one server, or use tlsFirst() where the server allows it: under TLS first, as on a plaintext connection or over wss://, the first INFO arrives inside TLS and is used in full. ignoreDiscoveredServers() turns the wait off together with the discovered servers.
Bytes that arrive after the INFO line and before the handshake are not acted on. The attempt fails at once as a TLS handshake failure whose message quotes the server's line as untrusted text, cut at 256 bytes with control characters escaped. A full nats-server that writes INFO followed by -ERR 'maximum connections exceeded' is reported that way. On a plaintext connection the same bytes are protocol and are processed normally, so the -ERR reaches the error listener.
nats-server writes each entry of connect_urls as host:port, with an IPv6 address in brackets, and never with a scheme. The client takes an entry as follows. User info before the host, as in user:pass@host:port, is dropped: the discovered server is sent the credentials the client uses for the server that reported it, those of that server's url or else those of the options. An entry that carries a scheme, nats://host:port or ws://host:port, is skipped as a whole, not reduced to its host and port: the transport and the TLS of a discovered server come from the server that reported it, never from the entry. An entry that does not parse as host:port once its user info is dropped, or whose port is outside 1 to 65535, is skipped as well. The other entries of the INFO are used. An INFO whose entries are all skipped leaves the pool with the configured servers and the current one: the servers learned from earlier INFOs are dropped, since the list is the cluster's current list and none of it is usable; an INFO without connect_urls, or with an empty list, changes nothing. An entry that names a configured server, by host and port as written, does not change that server. Each skipped entry is reported through ErrorListener.discoveredServerSkipped with the entry as the server sent it and the reason, each time an INFO carries it, unless the options ignore discovered servers; the logger and console listeners log it at WARNING with the entry quoted and control characters escaped by Encoding.quote, which a custom listener can use as well. The rule is NatsUri.discoveredHostPort.
A discovered server takes the scheme of the server that reported it: an entry learned over tls:// becomes a tls:// server, and one learned over wss:// a wss:// server, so a cluster reached over WebSocket is followed over WebSocket. A custom ServerPool receives the entries as host:port only, through ServerPool.acceptDiscoveredUrls, together with the server that reported them, and gives them a transport the same way; it never receives an entry with a scheme or with user info.