source: josm/trunk/test/unit/org/openstreetmap/josm/io/remotecontrol/RemoteControlTest.java @ 12849

Last change on this file since 12849 was 12849, checked in by bastiK, 15 months ago

see #15229 - use Config in tests

  • Property svn:eol-style set to native
File size: 5.4 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io.remotecontrol;
3
4import static org.junit.Assert.assertEquals;
5
6import java.io.BufferedReader;
7import java.io.IOException;
8import java.io.InputStream;
9import java.io.InputStreamReader;
10import java.net.HttpURLConnection;
11import java.net.URL;
12import java.nio.charset.StandardCharsets;
13import java.nio.file.Files;
14import java.nio.file.Paths;
15import java.security.GeneralSecurityException;
16import java.security.SecureRandom;
17import java.security.cert.X509Certificate;
18
19import javax.net.ssl.HostnameVerifier;
20import javax.net.ssl.HttpsURLConnection;
21import javax.net.ssl.SSLContext;
22import javax.net.ssl.TrustManager;
23import javax.net.ssl.X509TrustManager;
24
25import org.junit.After;
26import org.junit.Before;
27import org.junit.Test;
28import org.openstreetmap.josm.JOSMFixture;
29import org.openstreetmap.josm.spi.preferences.Config;
30import org.openstreetmap.josm.tools.Logging;
31
32import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
33
34/**
35 * Unit tests for Remote Control
36 */
37public class RemoteControlTest {
38
39    private String httpBase;
40    private String httpsBase;
41
42    /**
43     * Starts Remote control before testing requests.
44     * @throws GeneralSecurityException if a security error occurs
45     */
46    @Before
47    public void setUp() throws GeneralSecurityException {
48        JOSMFixture.createUnitTestFixture().init();
49        RemoteControl.PROP_REMOTECONTROL_HTTPS_ENABLED.put(true);
50        deleteKeystore();
51
52        RemoteControl.start();
53        disableCertificateValidation();
54        httpBase = "http://127.0.0.1:"+Config.getPref().getInt("remote.control.port", 8111);
55        httpsBase = "https://127.0.0.1:"+Config.getPref().getInt("remote.control.https.port", 8112);
56    }
57
58    /**
59     * Deletes JOSM keystore, if it exists.
60     */
61    public static void deleteKeystore() {
62        try {
63            Files.deleteIfExists(Paths.get(
64                    RemoteControl.getRemoteControlDir()).resolve(RemoteControlHttpsServer.KEYSTORE_FILENAME));
65        } catch (IOException e) {
66            Logging.error(e);
67        }
68    }
69
70    /**
71     * Disable all HTTPS validation mechanisms as described
72     * <a href="http://stackoverflow.com/a/2893932/2257172">here</a> and
73     * <a href="http://stackoverflow.com/a/19542614/2257172">here</a>
74     * @throws GeneralSecurityException if a security error occurs
75     */
76    public void disableCertificateValidation() throws GeneralSecurityException {
77        // Create a trust manager that does not validate certificate chains
78        TrustManager[] trustAllCerts = new TrustManager[] {
79            new X509TrustManager() {
80                @Override
81                @SuppressFBWarnings(value = "WEAK_TRUST_MANAGER")
82                public X509Certificate[] getAcceptedIssuers() {
83                    return new X509Certificate[0];
84                }
85
86                @Override
87                @SuppressFBWarnings(value = "WEAK_TRUST_MANAGER")
88                public void checkClientTrusted(X509Certificate[] certs, String authType) {
89                }
90
91                @Override
92                @SuppressFBWarnings(value = "WEAK_TRUST_MANAGER")
93                public void checkServerTrusted(X509Certificate[] certs, String authType) {
94                }
95            }
96        };
97
98        // Install the all-trusting trust manager
99        SSLContext sc = SSLContext.getInstance("TLS");
100        sc.init(null, trustAllCerts, new SecureRandom());
101        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
102
103        // Create all-trusting host name verifier
104        HostnameVerifier allHostsValid = (hostname, session) -> true;
105
106        // Install the all-trusting host verifier
107        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
108    }
109
110    /**
111     * Stops Remote control after testing requests.
112     */
113    @After
114    public void tearDown() {
115        RemoteControl.stop();
116    }
117
118    /**
119     * Tests that sending an HTTP request without command results in HTTP 400, with all available commands in error message.
120     * @throws Exception if an error occurs
121     */
122    @Test
123    public void testHttpListOfCommands() throws Exception {
124        testListOfCommands(httpBase);
125    }
126
127    /**
128     * Tests that sending an HTTPS request without command results in HTTP 400, with all available commands in error message.
129     * @throws Exception if an error occurs
130     */
131    @Test
132    public void testHttpsListOfCommands() throws Exception {
133        testListOfCommands(httpsBase);
134    }
135
136    private void testListOfCommands(String url) throws IOException, ReflectiveOperationException {
137        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
138        connection.connect();
139        assertEquals(connection.getResponseCode(), HttpURLConnection.HTTP_BAD_REQUEST);
140        try (InputStream is = connection.getErrorStream()) {
141            // TODO this code should be refactored somewhere in Utils as it is used in several JOSM classes
142            StringBuilder responseBody = new StringBuilder();
143            try (BufferedReader in = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
144                String s;
145                while ((s = in.readLine()) != null) {
146                    responseBody.append(s);
147                    responseBody.append("\n");
148                }
149            }
150            assert responseBody.toString().contains(RequestProcessor.getUsageAsHtml());
151        }
152    }
153}
Note: See TracBrowser for help on using the repository browser.