Post

Test HTTPS and Mutual TLS in REST Assured

Test an HTTPS API with a certificate the JVM doesn't trust, see why relaxedHTTPSValidation() is the wrong fix, trust the certificate with SSLConfig.trustStore(..), present a client certificate for mutual TLS, and pass a JDK SSLContext.

Test HTTPS and Mutual TLS in REST Assured

The bank’s staging API uses a self-signed certificate, and your first HTTPS test fails with a handshake error. Someone adds relaxedHTTPSValidation(), the error goes away, and so does every check TLS makes: months later, the suite would pass as happily through a misconfigured proxy. The partner API is stricter still: it requires mutual TLS, where the client presents a certificate too. In this guide, you’ll trust exactly the test certificate, keep the host name check, and present a client certificate in two ways.

Level: Advanced · Time: 25 minutes · Part of: Module 7: Authentication and Transport Security, section 5

What You’ll Build

You’ll build a test class called TlsAndMutualTlsTest with six tests, in two nested classes. ServerAuthentication shows an untrusted certificate failing, relaxed validation, and the right fix; MutualTls shows a refused client, a client certificate from a key store, and one from a JDK SSLContext.

One of the tests presents a client certificate, and checks what the server saw:

1
2
3
4
5
6
7
GET /api/v1/whoami HTTP/1.1
Host: localhost:<port>

HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8

{"protocol":"TLSv1.3","clientCertificate":"CN=tpp-client,O=Example TPP,C=NL"}

When you’re done, Maven reports six passing tests:

1
2
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

In this guide, you will:

  • Trust the server’s certificate.
  • Present a client certificate.
  • Pass a JDK SSLContext.

What You Need

How to Complete This Guide

You can work through this guide in one of two ways:

  • Build it step by step: create TlsAndMutualTlsTest in a new section_05 package next to the classes from the previous sections, and follow every heading below.
  • Skip ahead: open the finished class (TlsAndMutualTlsTest.java) and read along. You can run it at any time with the command in Run the Tests.

Get the code: if you haven’t cloned the examples repository yet, follow the steps in Test HTTP Basic Authentication in REST Assured.

Out of scope: this guide doesn’t cover creating certificates or certificate authorities; the module’s test key material is ready-made.

Understand TLS and Mutual TLS

The problem. Test environments rarely have certificates the JVM trusts. A local server, a staging API or a test container uses a self-signed certificate or one from an internal authority, and the first HTTPS request fails. The quick fix, turning certificate checking off, removes every protection TLS gives, and tests can no longer notice a broken or intercepted connection.

The concept. In a TLS handshake, the server presents a certificate, and the client checks that it was signed by an authority it trusts and that the host name matches: that proves the client is talking to the real server. In mutual TLS, the client presents a certificate too, and the server checks it: that proves who the client is, before any HTTP is exchanged. REST Assured configures both with SSLConfig:

SettingWhat it does
trustStore(path, password)The certificates the client trusts, from a key store file
keyStore(path, password)The client’s own key and certificate, for mutual TLS
sslContext(context)A JDK SSLContext built however you like, since REST Assured 6.3
relaxedHTTPSValidation()Trusts every certificate and every host name

When to use each. Trust the test environment’s certificate with sslConfig().trustStore(..), which keeps the host name check. Add keyStore(..) for mutual TLS, or pass an SSLContext when your application already builds one. Keep relaxedHTTPSValidation() for a quick experiment, never for a committed suite.

Trust exactly the certificate you mean to, and keep every other check on.

Meet the API Under Test

SecureAccountsApi serves GET /api/v1/whoami over HTTPS at https://localhost. It answers with the TLS protocol and the subject of the client certificate, if any:

1
{"protocol":"TLSv1.3","clientCertificate":"none"}

The test starts two instances: one with plain TLS, and one that requires a client certificate. The test key material is in src/test/resources/tls, with the password changeit, and is valid until 2036:

FileContains
client-truststore.p12The server’s self-signed certificate, CN=localhost, valid for localhost and 127.0.0.1
client.p12The client’s key and certificate, CN=tpp-client,O=Example TPP,C=NL

Your tests check these values:

  • Whether the handshake succeeds, and which exception it throws when it doesn’t.
  • The protocol the connection used.
  • The clientCertificate the server saw, which proves whether a client certificate was really presented.

Trust the Server’s Certificate

Set Up the Test Class

Goal: create the test class with both servers, two nested classes and a helper that finds an exception in a chain of causes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.javanibble.module_07.section_05;

import static io.restassured.RestAssured.given;
import static io.restassured.config.RestAssuredConfig.config;
import static io.restassured.config.SSLConfig.sslConfig;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertThrows;

import com.javanibble.auth.SecureAccountsApi;

import io.restassured.specification.RequestSpecification;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.TrustManagerFactory;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

class TlsAndMutualTlsTest {

    private static final String TRUST_STORE = "tls/client-truststore.p12";
    private static final String KEY_STORE = "tls/client.p12";
    private static final String PASSWORD = "changeit";

    private static SecureAccountsApi tls;
    private static SecureAccountsApi mutualTls;

    @BeforeAll
    static void startApis() {
        tls = SecureAccountsApi.startTls();
        mutualTls = SecureAccountsApi.startMutualTls();
    }

    @AfterAll
    static void stopApis() {
        tls.close();
        mutualTls.close();
    }

    private static RequestSpecification to(SecureAccountsApi api) {
        return given().baseUri(api.baseUri()).port(api.port());
    }

    @Nested
    class ServerAuthentication {
    }

    @Nested
    class MutualTls {
    }

    private static void assertCauseIs(Class<? extends Throwable> expected, Throwable thrown) {
        for (Throwable t = thrown; t != null; t = t.getCause()) {
            if (expected.isInstance(t)) {
                return;
            }
        }
        throw new AssertionError("Expected a " + expected.getSimpleName() + " in the causes of " + thrown, thrown);
    }
}

What’s happening:

  • tls serves plain HTTPS, and mutualTls refuses a handshake without a trusted client certificate.
  • to(api) points a request at one of them.
  • assertCauseIs(..) walks an exception’s chain of causes, because a failed handshake can arrive wrapped.

Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.

See an Untrusted Certificate Fail

Goal: show the handshake error a self-signed certificate causes.

Add this test to ServerAuthentication:

1
2
3
4
5
@Test
void anUntrustedCertificateFailsTheHandshake() {
    Exception exception = assertThrows(Exception.class, () -> to(tls).when().get("/api/v1/whoami"));
    assertCauseIs(SSLHandshakeException.class, exception);
}

What’s happening:

  • The server’s certificate is self-signed, so the JVM’s default trust store doesn’t know it.
  • The handshake fails with javax.net.ssl.SSLHandshakeException: (certificate_unknown) PKIX path building failed: ... unable to find valid certification path to requested target.
  • This is the error that tempts people to turn checking off.

Checkpoint: run TlsAndMutualTlsTest from your IDE. One test runs and passes.

See Relaxed Validation Pass

Goal: show that relaxed validation makes the error go away, and why that’s no fix.

Add this test to ServerAuthentication:

1
2
3
4
5
6
7
8
9
@Test
void relaxedValidationWorksButChecksNothing() {
    to(tls)
        .relaxedHTTPSValidation()
    .when()
        .get("/api/v1/whoami")
    .then()
        .statusCode(200);
}

What’s happening:

  • relaxedHTTPSValidation() trusts every certificate and every host name.
  • A misconfigured server, an expired certificate or a man in the middle all pass silently. That’s fine for a quick experiment, and wrong in a committed suite.

Checkpoint: run the class again. Two tests pass.

Trust the Server Certificate

Goal: trust exactly the test certificate, and keep the host name check.

Add this test to ServerAuthentication:

1
2
3
4
5
6
7
8
9
10
11
@Test
void trustTheServerCertificate() {
    to(tls)
        .config(config().sslConfig(sslConfig().trustStore(TRUST_STORE, PASSWORD)))
    .when()
        .get("/api/v1/whoami")
    .then()
        .statusCode(200)
        .body("protocol", startsWith("TLSv1."))
        .body("clientCertificate", equalTo("none"));
}

What’s happening:

  • sslConfig().trustStore(..) makes the client trust the certificate in the trust store, and nothing else.
  • The host name is still checked against the certificate.
  • The server answers with the protocol, TLSv1.3 here, and no client certificate.

Checkpoint: run the class again. Three tests pass.

Don’t use the given().trustStore(..) shortcut. It loads the same trust store, but it also turns the host name check off. Sent to https://localhost., a name the certificate doesn’t cover, the SSLConfig form fails with Certificate for <localhost.> doesn't match any of the subject alternative names: [localhost], while the shortcut and relaxedHTTPSValidation() both pass. Use config().sslConfig(sslConfig().trustStore(..)).

Present a Client Certificate

See the Server Refuse a Client Without One

Goal: prove that the mutual-TLS server refuses a client that has no certificate.

Add this test to MutualTls:

1
2
3
4
5
6
7
8
9
@Test
void withoutAClientCertificateTheServerRefuses() {
    Exception exception = assertThrows(Exception.class, () ->
        to(mutualTls)
            .config(config().sslConfig(sslConfig().trustStore(TRUST_STORE, PASSWORD)))
        .when()
            .get("/api/v1/whoami"));
    assertCauseIs(IOException.class, exception);
}

What’s happening:

  • The client trusts the server, but has no certificate of its own, so the server ends the handshake.
  • On this JDK, the client sees SSLHandshakeException: (certificate_required) Received fatal alert: certificate_required. Depending on the JDK and timing it can also be a reset connection, so the test accepts any IOException in the causes.
  • There’s no HTTP status to check: the request never got that far.

Checkpoint: run the class again. Four tests pass.

Expect an exception, not a status, from a failed handshake. A rejected client certificate fails before HTTP, so then().statusCode(..) is never reached.

Present a Certificate From a Key Store

Goal: add the client’s key and certificate, and check what the server saw.

Add this test to MutualTls:

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void presentAClientCertificateFromAKeyStore() {
    to(mutualTls)
        .config(config().sslConfig(sslConfig()
                .trustStore(TRUST_STORE, PASSWORD)
                .keyStore(KEY_STORE, PASSWORD)))
    .when()
        .get("/api/v1/whoami")
    .then()
        .statusCode(200)
        .body("clientCertificate", equalTo("CN=tpp-client,O=Example TPP,C=NL"));
}

What’s happening:

  • keyStore(..) adds the client’s key and certificate to the handshake, next to the trust store.
  • The server reports the subject of the certificate the client presented, which proves the client certificate was really used.
  • A test that passes with or without the client certificate proves nothing, so always check something the server learned from it.

Checkpoint: run the class again. Five tests pass.

Pass a JDK SSLContext

Build the Context Yourself

Goal: give REST Assured a JDK SSLContext with the client’s keys and the trusted certificate.

Add this test and these helpers to MutualTls:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Test
void orGiveRestAssuredAJdkSslContext() throws Exception {
    to(mutualTls)
        .config(config().sslConfig(sslConfig().sslContext(sslContext())))
    .when()
        .get("/api/v1/whoami")
    .then()
        .statusCode(200)
        .body("clientCertificate", startsWith("CN=tpp-client"));
}

private static SSLContext sslContext() throws GeneralSecurityException, IOException {
    KeyManagerFactory keys = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keys.init(load(KEY_STORE), PASSWORD.toCharArray());
    TrustManagerFactory trust = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trust.init(load(TRUST_STORE));
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(keys.getKeyManagers(), trust.getTrustManagers(), null);
    return context;
}

private static KeyStore load(String resource) throws GeneralSecurityException, IOException {
    try (InputStream in = TlsAndMutualTlsTest.class.getClassLoader().getResourceAsStream(resource)) {
        KeyStore store = KeyStore.getInstance("PKCS12");
        store.load(in, PASSWORD.toCharArray());
        return store;
    }
}

What’s happening:

  • sslConfig().sslContext(..), new in REST Assured 6.3, takes a standard JDK SSLContext, and REST Assured uses it as it is.
  • sslContext() builds one from the JDK’s key and trust managers, loading both PKCS12 files from the classpath.
  • You could get the context from wherever your application already builds one instead, such as a PEM file loader or a hardware security module.

Checkpoint: run the class again. All six tests pass.

Test key stores like these belong in a repository only because they protect nothing. Real client keys belong in a secret store, never in source control.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-07 -Dtest=TlsAndMutualTlsTest

You should see a result similar to the following, with one line per nested class:

1
2
3
4
5
6
7
8
9
[INFO] Running com.javanibble.module_07.section_05.TlsAndMutualTlsTest
[INFO] Running com.javanibble.module_07.section_05.TlsAndMutualTlsTest$MutualTls
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.417 s -- in com.javanibble.module_07.section_05.TlsAndMutualTlsTest$MutualTls
[INFO] Running com.javanibble.module_07.section_05.TlsAndMutualTlsTest$ServerAuthentication
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.032 s -- in com.javanibble.module_07.section_05.TlsAndMutualTlsTest$ServerAuthentication
[INFO]
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

In trustTheServerCertificate, delete the .config(config().sslConfig(..)) line and run the command again. You should see a result similar to the following:

1
2
[ERROR] Errors:
[ERROR]   TlsAndMutualTlsTest.trustTheServerCertificate » SSLHandshake (certificate_unknown) PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Without the trust store, the client falls back to the JVM’s default trust store, which doesn’t know the self-signed certificate. JUnit reports an error, not a failure, because the handshake threw before any assertion ran. PKIX path building failed always means the same thing: the client doesn’t trust the certificate, so check the trust store, not the server.

Put the .config(..) line back and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
SSLHandshakeException: ... PKIX path building failedThe client doesn’t trust the server’s certificateAdd the certificate with sslConfig().trustStore(..)
SSLException: Certificate for <..> doesn't match any of the subject alternative namesThe host name isn’t in the certificateUse a host name the certificate covers, such as localhost
SSLHandshakeException: (certificate_required)The server requires a client certificateAdd keyStore(..), or an SSLContext with key managers
A test passes against a server with the wrong certificaterelaxedHTTPSValidation() or given().trustStore(..) turned checks offUse config().sslConfig(sslConfig().trustStore(..))

Try It Yourself

Exercise 1: Prove the Host Name Is Still Checked

Add a test to ServerAuthentication called theHostNameIsStillChecked. Send a request to https://localhost., with a trailing dot, which resolves to the same server but isn’t a name in the certificate. Check that the SSLConfig trust store makes it fail with an SSLException in the causes, and that the given().trustStore(..) shortcut lets it through with 200.

Hint

Build the request with given().baseUri("https://localhost.").port(tls.port()) instead of to(tls). SSLException is in javax.net.ssl.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
void theHostNameIsStillChecked() {
    Exception exception = assertThrows(Exception.class, () ->
        given().baseUri("https://localhost.").port(tls.port())
            .config(config().sslConfig(sslConfig().trustStore(TRUST_STORE, PASSWORD)))
        .when()
            .get("/api/v1/whoami"));
    assertCauseIs(SSLException.class, exception);

    given().baseUri("https://localhost.").port(tls.port())
        .trustStore(TRUST_STORE, PASSWORD)
    .when()
        .get("/api/v1/whoami")
    .then()
        .statusCode(200);
}

Add import javax.net.ssl.SSLException; to the class.

Exercise 2: Refuse an SSLContext Without Keys

Add a test to MutualTls called anSslContextWithoutKeysIsRefused. Build an SSLContext that trusts the server but has no key managers, and check that the mutual-TLS server refuses it with an IOException in the causes. Then, as a positive control, check with the key store that the connection uses TLSv1.3 and presents a certificate from O=Example TPP.

Hint

Pass null as the key managers to context.init(..). Reuse load(..) for the trust store, and containsString(..) for the organisation in the certificate subject.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Test
void anSslContextWithoutKeysIsRefused() throws Exception {
    TrustManagerFactory trust = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trust.init(load(TRUST_STORE));
    SSLContext trustOnly = SSLContext.getInstance("TLS");
    trustOnly.init(null, trust.getTrustManagers(), null);

    Exception exception = assertThrows(Exception.class, () ->
        to(mutualTls)
            .config(config().sslConfig(sslConfig().sslContext(trustOnly)))
        .when()
            .get("/api/v1/whoami"));
    assertCauseIs(IOException.class, exception);

    to(mutualTls)
        .config(config().sslConfig(sslConfig().trustStore(TRUST_STORE, PASSWORD).keyStore(KEY_STORE, PASSWORD)))
    .when()
        .get("/api/v1/whoami")
    .then()
        .statusCode(200)
        .body("protocol", equalTo("TLSv1.3"))
        .body("clientCertificate", containsString("O=Example TPP"));
}

Add import static org.hamcrest.Matchers.containsString; to the class.

Summary

You built TlsAndMutualTlsTest, which shows an untrusted certificate failing, relaxed validation checking nothing, the right fix with a trust store, a refused client, and a client certificate from a key store and from a JDK SSLContext. The staging certificate is trusted, and nothing else is.

  • A self-signed test certificate fails the handshake with PKIX path building failed.
  • The right fix is sslConfig().trustStore(..), which trusts that one certificate and keeps the host name check; relaxedHTTPSValidation() and given().trustStore(..) both turn checks off.
  • For mutual TLS, add the client’s key and certificate with keyStore(..), or pass a JDK SSLContext with sslContext(..), new in REST Assured 6.3.
  • A refused client certificate fails before HTTP, so expect an exception and look for its cause.
  • Prove a client certificate was used by checking what the server saw, such as its subject.

Here are the commands you used in this guide:

1
mvn test -pl module-07 -Dtest=TlsAndMutualTlsTest

What’s Next

Next: continue with Keep Credentials Off Cross-Origin Redirects in REST Assured, which checks that credentials aren’t sent along when a redirect leads to another server.

The code:

Go deeper:

Related guides:

This post is licensed under CC BY 4.0 by the author.