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