]> WPIA git - gigi.git/blob - tests/org/cacert/gigi/testUtils/ManagedTest.java
UPD: Abstracted web interactions
[gigi.git] / tests / org / cacert / gigi / testUtils / ManagedTest.java
1 package org.cacert.gigi.testUtils;
2
3 import static org.junit.Assert.*;
4
5 import java.io.BufferedReader;
6 import java.io.DataOutputStream;
7 import java.io.FileInputStream;
8 import java.io.IOException;
9 import java.io.InputStreamReader;
10 import java.io.OutputStream;
11 import java.io.UnsupportedEncodingException;
12 import java.net.HttpURLConnection;
13 import java.net.InetSocketAddress;
14 import java.net.MalformedURLException;
15 import java.net.Socket;
16 import java.net.URL;
17 import java.net.URLConnection;
18 import java.net.URLEncoder;
19 import java.nio.file.Files;
20 import java.nio.file.Paths;
21 import java.security.KeyManagementException;
22 import java.security.NoSuchAlgorithmException;
23 import java.security.Principal;
24 import java.security.PrivateKey;
25 import java.security.cert.X509Certificate;
26 import java.sql.PreparedStatement;
27 import java.sql.ResultSet;
28 import java.sql.SQLException;
29 import java.util.Properties;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
32
33 import javax.net.ssl.HttpsURLConnection;
34 import javax.net.ssl.KeyManager;
35 import javax.net.ssl.SSLContext;
36 import javax.net.ssl.X509KeyManager;
37
38 import org.cacert.gigi.DevelLauncher;
39 import org.cacert.gigi.database.DatabaseConnection;
40 import org.cacert.gigi.testUtils.TestEmailReciever.TestMail;
41 import org.cacert.gigi.util.DatabaseManager;
42 import org.cacert.gigi.util.SimpleSigner;
43 import org.junit.After;
44 import org.junit.AfterClass;
45 import org.junit.BeforeClass;
46
47 public class ManagedTest {
48         /**
49          * Some password that fullfills the password criteria.
50          */
51         protected static final String TEST_PASSWORD = "xvXV12°§";
52
53         private final String registerService = "/register";
54
55         private static TestEmailReciever ter;
56         private static Process gigi;
57         private static String url = "localhost:4443";
58
59         public static String getServerName() {
60                 return url;
61         }
62
63         static Properties testProps = new Properties();
64         static {
65                 InitTruststore.run();
66                 HttpURLConnection.setFollowRedirects(false);
67         }
68
69         @BeforeClass
70         public static void connectToServer() {
71                 try {
72                         testProps.load(new FileInputStream("config/test.properties"));
73                         if (!DatabaseConnection.isInited()) {
74                                 DatabaseConnection.init(testProps);
75                         }
76                         System.out.println("... purging Database");
77                         DatabaseManager.run(new String[] { testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"),
78                                         testProps.getProperty("sql.user"), testProps.getProperty("sql.password") });
79
80                         String type = testProps.getProperty("type");
81                         if (type.equals("local")) {
82                                 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
83                                 String[] parts = testProps.getProperty("mail").split(":", 2);
84                                 ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
85                                 return;
86                         }
87                         url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
88                         gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
89                         DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
90                         System.out.println("... starting server");
91                         Properties mainProps = new Properties();
92                         mainProps.setProperty("host", "127.0.0.1");
93                         mainProps.setProperty("name.secure", testProps.getProperty("name.secure"));
94                         mainProps.setProperty("name.www", testProps.getProperty("name.www"));
95                         mainProps.setProperty("name.static", testProps.getProperty("name.static"));
96
97                         mainProps.setProperty("port", testProps.getProperty("serverPort"));
98                         mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider");
99                         mainProps.setProperty("emailProvider.port", "8473");
100                         mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
101                         mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
102                         mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
103                         mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
104
105                         byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
106                         byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
107
108                         DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts,
109                                 keystore);
110                         toGigi.flush();
111
112                         final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream()));
113                         String line;
114                         while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) {
115                         }
116                         new Thread() {
117                                 @Override
118                                 public void run() {
119                                         String line;
120                                         try {
121                                                 while ((line = br.readLine()) != null) {
122                                                         System.err.println(line);
123                                                 }
124                                         } catch (IOException e) {
125                                                 e.printStackTrace();
126                                         }
127                                 }
128                         }.start();
129                         if (line == null) {
130                                 throw new Error("Server startup failed");
131                         }
132                         ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473));
133                         SimpleSigner.runSigner();
134                 } catch (IOException e) {
135                         throw new Error(e);
136                 } catch (ClassNotFoundException e1) {
137                         e1.printStackTrace();
138                 } catch (SQLException e1) {
139                         e1.printStackTrace();
140                 } catch (InterruptedException e) {
141                         e.printStackTrace();
142                 }
143
144         }
145
146         @AfterClass
147         public static void tearDownServer() {
148                 String type = testProps.getProperty("type");
149                 ter.destroy();
150                 if (type.equals("local")) {
151                         return;
152                 }
153                 gigi.destroy();
154                 try {
155                         SimpleSigner.stopSigner();
156                 } catch (InterruptedException e) {
157                         e.printStackTrace();
158                 }
159         }
160
161         @After
162         public void removeMails() {
163                 ter.reset();
164         }
165
166         public TestMail waitForMail() {
167                 try {
168                         return ter.recieve();
169                 } catch (InterruptedException e) {
170                         throw new Error(e);
171                 }
172         }
173
174         public static TestEmailReciever getMailReciever() {
175                 return ter;
176         }
177
178         public String runRegister(String param) throws IOException {
179                 URL regist = new URL("https://" + getServerName() + registerService);
180                 HttpURLConnection uc = (HttpURLConnection) regist.openConnection();
181                 HttpURLConnection csrfConn = (HttpURLConnection) regist.openConnection();
182
183                 String headerField = csrfConn.getHeaderField("Set-Cookie");
184                 headerField = stripCookie(headerField);
185
186                 String csrf = getCSRF(csrfConn);
187                 uc.addRequestProperty("Cookie", headerField);
188                 uc.setDoOutput(true);
189                 uc.getOutputStream().write((param + "&csrf=" + csrf).getBytes());
190                 String d = IOUtils.readURL(uc);
191                 return d;
192         }
193
194         public String fetchStartErrorMessage(String d) throws IOException {
195                 String formFail = "<div class='formError'>";
196                 int idx = d.indexOf(formFail);
197                 if (idx == -1) {
198                         return null;
199                 }
200                 String startError = d.substring(idx + formFail.length(), idx + 100).trim();
201                 return startError;
202         }
203
204         public void registerUser(String firstName, String lastName, String email, String password) {
205                 try {
206                         String query = "fname=" + URLEncoder.encode(firstName, "UTF-8") + "&lname="
207                                 + URLEncoder.encode(lastName, "UTF-8") + "&email=" + URLEncoder.encode(email, "UTF-8") + "&pword1="
208                                 + URLEncoder.encode(password, "UTF-8") + "&pword2=" + URLEncoder.encode(password, "UTF-8")
209                                 + "&day=1&month=1&year=1910&cca_agree=1";
210                         String data = fetchStartErrorMessage(runRegister(query));
211                         assertTrue(data, data.startsWith("</div>"));
212                 } catch (UnsupportedEncodingException e) {
213                         throw new Error(e);
214                 } catch (IOException e) {
215                         throw new Error(e);
216                 }
217         }
218
219         public int createVerifiedUser(String firstName, String lastName, String email, String password) {
220                 registerUser(firstName, lastName, email, password);
221                 try {
222                         TestMail tm = ter.recieve();
223                         String verifyLink = tm.extractLink();
224                         String[] parts = verifyLink.split("\\?");
225                         URL u = new URL("https://" + getServerName() + "/verify?" + parts[1]);
226                         u.openStream().close();
227                         ;
228                         PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM users where email=?");
229                         ps.setString(1, email);
230                         ResultSet rs = ps.executeQuery();
231                         if (rs.next()) {
232                                 return rs.getInt(1);
233                         }
234                         throw new Error();
235                 } catch (InterruptedException e) {
236                         throw new Error(e);
237                 } catch (IOException e) {
238                         throw new Error(e);
239                 } catch (SQLException e) {
240                         throw new Error(e);
241                 }
242         }
243
244         /**
245          * Creates a new user with 100 Assurance points given by an (invalid)
246          * assurance.
247          * 
248          * @param firstName
249          *            the first name
250          * @param lastName
251          *            the last name
252          * @param email
253          *            the email
254          * @param password
255          *            the password
256          * @return a new userid.
257          */
258         public int createAssuranceUser(String firstName, String lastName, String email, String password) {
259                 int uid = createVerifiedUser(firstName, lastName, email, password);
260                 try {
261                         PreparedStatement ps = DatabaseConnection.getInstance().prepare(
262                                 "INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
263                         ps.setInt(1, uid);
264                         ps.setInt(2, 0);
265                         ps.execute();
266                         ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
267                         ps.setInt(1, uid);
268                         ps.setInt(2, uid);
269                         ps.execute();
270
271                 } catch (SQLException e) {
272                         throw new Error(e);
273                 }
274                 return uid;
275         }
276
277         static int count = 0;
278
279         public String createUniqueName() {
280                 return "test" + System.currentTimeMillis() + "a" + (count++);
281         }
282
283         private String stripCookie(String headerField) {
284                 return headerField.substring(0, headerField.indexOf(';'));
285         }
286
287         public static final String SECURE_REFERENCE = "/account/certs/email";
288
289         public boolean isLoggedin(String cookie) throws IOException {
290                 URL u = new URL("https://" + getServerName() + SECURE_REFERENCE);
291                 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
292                 huc.addRequestProperty("Cookie", cookie);
293                 return huc.getResponseCode() == 200;
294         }
295
296         public String login(String email, String pw) throws IOException {
297                 URL u = new URL("https://" + getServerName() + "/login");
298                 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
299                 huc.setDoOutput(true);
300                 OutputStream os = huc.getOutputStream();
301                 String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8");
302                 os.write(data.getBytes());
303                 os.flush();
304                 String headerField = huc.getHeaderField("Set-Cookie");
305                 return stripCookie(headerField);
306         }
307
308         public String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException,
309                 KeyManagementException, IOException, MalformedURLException {
310
311                 HttpURLConnection connection = (HttpURLConnection) new URL("https://"
312                         + getServerName().replaceFirst("^www.", "secure.") + "/login").openConnection();
313                 authenticateClientCert(pk, ce, connection);
314                 if (connection.getResponseCode() == 302) {
315                         assertEquals("https://" + getServerName().replaceFirst("^www.", "secure.").replaceFirst(":443$", "") + "/",
316                                 connection.getHeaderField("Location").replaceFirst(":443$", ""));
317                         return stripCookie(connection.getHeaderField("Set-Cookie"));
318                 } else {
319                         return null;
320                 }
321         }
322
323         public void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection)
324                 throws NoSuchAlgorithmException, KeyManagementException {
325                 KeyManager km = new X509KeyManager() {
326
327                         @Override
328                         public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
329                                 return "client";
330                         }
331
332                         @Override
333                         public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
334                                 return null;
335                         }
336
337                         @Override
338                         public X509Certificate[] getCertificateChain(String arg0) {
339                                 return new X509Certificate[] { ce };
340                         }
341
342                         @Override
343                         public String[] getClientAliases(String arg0, Principal[] arg1) {
344                                 return new String[] { "client" };
345                         }
346
347                         @Override
348                         public PrivateKey getPrivateKey(String arg0) {
349                                 if (arg0.equals("client")) {
350                                         return pk;
351                                 }
352                                 return null;
353                         }
354
355                         @Override
356                         public String[] getServerAliases(String arg0, Principal[] arg1) {
357                                 return new String[] { "client" };
358                         }
359                 };
360                 SSLContext sc = SSLContext.getInstance("TLS");
361                 sc.init(new KeyManager[] { km }, null, null);
362                 if (connection instanceof HttpsURLConnection) {
363                         ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
364                 }
365         }
366
367         public String getCSRF(URLConnection u) throws IOException {
368                 String content = IOUtils.readURL(u);
369                 Pattern p = Pattern.compile("<input type='hidden' name='csrf' value='([^']+)'>");
370                 Matcher m = p.matcher(content);
371                 if (!m.find()) {
372                         throw new Error("No CSRF Token");
373                 }
374                 return m.group(1);
375         }
376
377         public static String[] generateCSR(String dn) throws IOException {
378                 Process p = Runtime.getRuntime().exec(
379                         new String[] { "openssl", "req", "-newkey", "rsa:1024", "-nodes", "-subj", dn, "-config",
380                                         "keys/selfsign.config" });
381                 String csr = IOUtils.readURL(new InputStreamReader(p.getInputStream()));
382
383                 String[] parts = csr.split("(?<=-----)\n(?=-----)");
384                 if (parts.length != 2) {
385                         System.err.println(IOUtils.readURL(new InputStreamReader(p.getErrorStream())));
386                         throw new Error();
387                 }
388                 return parts;
389         }
390
391         public String executeBasicWebInteraction(String cookie, String path, String query) throws IOException,
392                 MalformedURLException, UnsupportedEncodingException {
393                 URLConnection uc = new URL("https://" + getServerName() + path).openConnection();
394                 uc.addRequestProperty("Cookie", cookie);
395                 String csrf = getCSRF(uc);
396
397                 uc = new URL("https://" + getServerName() + path).openConnection();
398                 uc.addRequestProperty("Cookie", cookie);
399                 uc.setDoOutput(true);
400                 OutputStream os = uc.getOutputStream();
401                 os.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" //
402                 + query//
403                 ).getBytes());
404                 os.flush();
405                 String error = fetchStartErrorMessage(IOUtils.readURL(uc));
406                 return error;
407         }
408
409 }