View Javadoc
1   /*
2    * Copyright (c) 2002-2025 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit;
16  
17  import static org.eclipse.jetty.http.HttpVersion.HTTP_1_1;
18  
19  import java.net.URL;
20  
21  import javax.net.ssl.SSLHandshakeException;
22  
23  import org.eclipse.jetty.server.SslConnectionFactory;
24  import org.eclipse.jetty.util.ssl.SslContextFactory;
25  import org.eclipse.jetty.util.ssl.SslContextFactory.Server;
26  import org.htmlunit.junit.BrowserRunner;
27  import org.junit.Test;
28  import org.junit.runner.RunWith;
29  
30  /**
31   * Tests for custom trust store.
32   *
33   * @author Carsten Steul
34   * @author Ahmed Ashour
35   * @author Ronald Brill
36   */
37  @RunWith(BrowserRunner.class)
38  public class HttpWebConnectionTruststoreTest extends WebServerTestCase {
39  
40      /**
41       * @throws Exception if an error occurs
42       */
43      @Test
44      public void selfSignedCertInTruststore() throws Exception {
45          final WebClient webClient = getWebClient();
46          webClient.getOptions().setSSLTrustStore(
47                  getClass().getClassLoader().getResource("self-signed-cert.keystore"),
48                  "nopassword", "jks");
49  
50          final URL https = new URL("https://localhost:" + PORT2 + "/");
51          loadPage("<div>test</div>", https);
52      }
53  
54      /**
55       * @throws Exception if an error occurs
56       */
57      @Test(expected = SSLHandshakeException.class)
58      public void selfSignedCertNotInTruststore() throws Exception {
59          final URL https = new URL("https://localhost:" + PORT2 + "/");
60          loadPage("<div>test</div>", https);
61      }
62  
63      @Override
64      protected boolean isHttps() {
65          return true;
66      }
67  
68      @Override
69      public SslConnectionFactory getSslConnectionFactory() {
70          final URL url = HttpWebConnectionInsecureSSLWithClientCertificateTest.class
71                  .getClassLoader().getResource("self-signed-cert.keystore");
72  
73          final SslContextFactory contextFactory = new Server.Server();
74          contextFactory.setKeyStoreType("jks");
75          contextFactory.setKeyStorePath(url.toExternalForm());
76          contextFactory.setKeyStorePassword("nopassword");
77          return new SslConnectionFactory(contextFactory, HTTP_1_1.toString());
78      }
79  }