]> WPIA git - gigi.git/blob - tests/club/wpia/gigi/testUtils/ManagedTest.java
fix: ResultSet.getDate is often wrong as it fetches day-precision times
[gigi.git] / tests / club / wpia / gigi / testUtils / ManagedTest.java
1 package club.wpia.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.hamcrest.CoreMatchers;
37 import org.junit.After;
38 import org.junit.AfterClass;
39 import org.junit.BeforeClass;
40
41 import club.wpia.gigi.DevelLauncher;
42 import club.wpia.gigi.GigiApiException;
43 import club.wpia.gigi.database.GigiPreparedStatement;
44 import club.wpia.gigi.database.GigiResultSet;
45 import club.wpia.gigi.dbObjects.EmailAddress;
46 import club.wpia.gigi.dbObjects.Group;
47 import club.wpia.gigi.dbObjects.Job;
48 import club.wpia.gigi.dbObjects.ObjectCache;
49 import club.wpia.gigi.dbObjects.User;
50 import club.wpia.gigi.pages.account.MyDetails;
51 import club.wpia.gigi.pages.main.RegisterPage;
52 import club.wpia.gigi.testUtils.TestEmailReceiver.TestMail;
53 import club.wpia.gigi.util.SimpleSigner;
54
55 /**
56  * Base class for test suites who require a launched Gigi instance. The instance
57  * is cleared once per test suite.
58  */
59 public class ManagedTest extends ConfiguredTest {
60
61     static {
62         System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
63     }
64
65     private static TestEmailReceiver ter;
66
67     private static Process gigi;
68
69     private static String url = "localhost:4443";
70
71     private static String acceptLanguage = null;
72
73     public static void setAcceptLanguage(String acceptLanguage) {
74         ManagedTest.acceptLanguage = acceptLanguage;
75     }
76
77     public static String getServerName() {
78         return url.replaceFirst(":443$", "");
79     }
80
81     public static String getSecureServerName() {
82         return getServerName().replaceAll("^www\\.", "secure.");
83     }
84
85     static {
86         InitTruststore.run();
87         HttpURLConnection.setFollowRedirects(false);
88     }
89
90     @BeforeClass
91     public static void initEnvironmentHook() {
92         initEnvironment();
93     }
94
95     private static boolean inited = false;
96
97     public static Properties initEnvironment() {
98         try {
99             Properties mainProps = ConfiguredTest.initEnvironment();
100             if (inited) {
101                 return mainProps;
102             }
103             inited = true;
104             purgeDatabase();
105             String type = testProps.getProperty("type");
106             generateMainProps(mainProps);
107             if (type.equals("local")) {
108                 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort.https");
109                 String[] parts = testProps.getProperty("mail").split(":", 2);
110                 ter = new TestEmailReceiver(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
111                 ter.start();
112                 if (testProps.getProperty("withSigner", "false").equals("true")) {
113                     SimpleSigner.runSigner();
114                 }
115                 return mainProps;
116             }
117             url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort.https");
118             gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
119             DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
120             System.out.println("... starting server");
121
122             byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
123             byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
124
125             DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes("UTF-8"), "changeit".getBytes("UTF-8"), mainProps, cacerts, keystore);
126             toGigi.flush();
127
128             final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream(), "UTF-8"));
129             String line;
130             while ((line = br.readLine()) != null && !line.contains("System successfully started.")) {
131                 System.err.println(line);
132             }
133             new Thread() {
134
135                 @Override
136                 public void run() {
137                     String line;
138                     try {
139                         while ((line = br.readLine()) != null) {
140                             System.err.println(line);
141                         }
142                     } catch (IOException e) {
143                         e.printStackTrace();
144                     }
145                 }
146             }.start();
147             if (line == null) {
148                 throw new Error("Server startup failed");
149             }
150             ter = new TestEmailReceiver(new InetSocketAddress("localhost", 8473));
151             ter.start();
152             SimpleSigner.runSigner();
153             return mainProps;
154         } catch (IOException e) {
155             throw new Error(e);
156         } catch (SQLException e1) {
157             throw new Error(e1);
158         } catch (InterruptedException e) {
159             throw new Error(e);
160         }
161
162     }
163
164     protected static void await(Job j) throws InterruptedException {
165         SimpleSigner.ping();
166         j.waitFor(5000);
167     }
168
169     public static void purgeDatabase() throws SQLException, IOException {
170         purgeOnlyDB();
171         clearCaches();
172     }
173
174     public static void clearCaches() throws IOException {
175         ObjectCache.clearAllCaches();
176         // String type = testProps.getProperty("type");
177         URL u = new URL("https://" + getServerName() + "/manage");
178         u.openConnection().getHeaderField("Location");
179     }
180
181     private static void generateMainProps(Properties mainProps) {
182         mainProps.setProperty("testrunner", "true");
183         mainProps.setProperty("host", "127.0.0.1");
184
185         mainProps.setProperty("emailProvider", "club.wpia.gigi.email.TestEmailProvider");
186         mainProps.setProperty("emailProvider.port", "8473");
187         mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
188         mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
189         mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
190         mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
191         mainProps.setProperty("testing", "true");
192     }
193
194     @AfterClass
195     public static void tearDownServer() {
196         String type = testProps.getProperty("type");
197         ter.destroy();
198         if (type.equals("local")) {
199             return;
200         }
201         gigi.destroy();
202         try {
203             SimpleSigner.stopSigner();
204         } catch (InterruptedException e) {
205             e.printStackTrace();
206         }
207     }
208
209     public final String uniq = createUniqueName();
210
211     @After
212     public void removeMails() {
213         ter.reset();
214     }
215
216     @After
217     public void clearAcceptLanguage() {
218         ManagedTest.setAcceptLanguage(null);
219     }
220
221     @Override
222     public MailReceiver getMailReceiver() {
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("UTF-8"));
242         if (uc.getResponseCode() == 302) {
243             return "";
244         }
245         String d = IOUtils.readURL(uc);
246         return d;
247     }
248
249     public static org.hamcrest.Matcher<String> hasError() {
250         return CoreMatchers.containsString("<div class='alert alert-danger error-msgs'>");
251     }
252
253     public static org.hamcrest.Matcher<String> hasNoError() {
254         return CoreMatchers.not(hasError());
255     }
256
257     public static String fetchStartErrorMessage(String d) throws IOException {
258         String formFail = "<div class='alert alert-danger error-msgs'>";
259         int idx = d.indexOf(formFail);
260         if (idx == -1) {
261             return null;
262         }
263         String startError = d.substring(idx + formFail.length(), idx + formFail.length() + 150).trim();
264         return startError;
265     }
266
267     public static void registerUser(String firstName, String lastName, String email, String password) {
268         try {
269             String query = "name-type=western&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&tos_agree=1";
270             String data = fetchStartErrorMessage(runRegister(query));
271             assertNull(data);
272         } catch (UnsupportedEncodingException e) {
273             throw new Error(e);
274         } catch (IOException e) {
275             throw new Error(e);
276         }
277     }
278
279     public static int createVerifiedUser(String firstName, String lastName, String email, String password) {
280         registerUser(firstName, lastName, email, password);
281         try {
282             ter.receive().verify();
283
284             try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `users` WHERE `email`=?")) {
285                 ps.setString(1, email);
286
287                 GigiResultSet rs = ps.executeQuery();
288                 if (rs.next()) {
289                     return rs.getInt(1);
290                 }
291             }
292
293             throw new Error();
294         } catch (IOException e) {
295             throw new Error(e);
296         }
297     }
298
299     public static void grant(User u, Group g) throws IOException, GigiApiException {
300         u.grantGroup(getSupporter(), g);
301         clearCaches();
302     }
303
304     /**
305      * Creates a new user with 100 Verification Points given by an (invalid)
306      * verification.
307      * 
308      * @param firstName
309      *            the first name
310      * @param lastName
311      *            the last name
312      * @param email
313      *            the email
314      * @param password
315      *            the password
316      * @return a new userid.
317      */
318     public static int createAssuranceUser(String firstName, String lastName, String email, String password) {
319         int uid = createVerifiedUser(firstName, lastName, email, password);
320
321         makeAssurer(uid);
322
323         return uid;
324     }
325
326     protected static String stripCookie(String headerField) {
327         return headerField.substring(0, headerField.indexOf(';'));
328     }
329
330     public static final String SECURE_REFERENCE = MyDetails.PATH;
331
332     public static boolean isLoggedin(String cookie) throws IOException {
333         URL u = new URL("https://" + getServerName() + SECURE_REFERENCE);
334         HttpURLConnection huc = (HttpURLConnection) u.openConnection();
335         huc.addRequestProperty("Cookie", cookie);
336         return huc.getResponseCode() == 200;
337     }
338
339     public static String login(String email, String pw) throws IOException {
340         URL u = new URL("https://" + getServerName() + "/login");
341         HttpURLConnection huc = (HttpURLConnection) u.openConnection();
342
343         String csrf = getCSRF(huc);
344         String headerField = stripCookie(huc.getHeaderField("Set-Cookie"));
345
346         huc = (HttpURLConnection) u.openConnection();
347         cookie(huc, headerField);
348         huc.setDoOutput(true);
349         OutputStream os = huc.getOutputStream();
350         String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8") + "&csrf=" + URLEncoder.encode(csrf, "UTF-8");
351         os.write(data.getBytes("UTF-8"));
352         os.flush();
353         headerField = huc.getHeaderField("Set-Cookie");
354         if (headerField == null) {
355             return "";
356         }
357         if (huc.getResponseCode() != 302) {
358             fail(fetchStartErrorMessage(IOUtils.readURL(huc)));
359         }
360         return stripCookie(headerField);
361     }
362
363     public static String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException, KeyManagementException, IOException, MalformedURLException {
364
365         HttpURLConnection connection = (HttpURLConnection) new URL("https://" + getSecureServerName() + "/login").openConnection();
366         authenticateClientCert(pk, ce, connection);
367         if (connection.getResponseCode() == 302) {
368             assertEquals("https://" + getSecureServerName() + "/", connection.getHeaderField("Location").replaceFirst(":443$", ""));
369             return stripCookie(connection.getHeaderField("Set-Cookie"));
370         } else {
371             return null;
372         }
373     }
374
375     public static void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {
376         KeyManager km = new X509KeyManager() {
377
378             @Override
379             public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
380                 return "client";
381             }
382
383             @Override
384             public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
385                 return null;
386             }
387
388             @Override
389             public X509Certificate[] getCertificateChain(String arg0) {
390                 return new X509Certificate[] {
391                         ce
392                 };
393             }
394
395             @Override
396             public String[] getClientAliases(String arg0, Principal[] arg1) {
397                 return new String[] {
398                         "client"
399                 };
400             }
401
402             @Override
403             public PrivateKey getPrivateKey(String arg0) {
404                 if (arg0.equals("client")) {
405                     return pk;
406                 }
407                 return null;
408             }
409
410             @Override
411             public String[] getServerAliases(String arg0, Principal[] arg1) {
412                 return new String[] {
413                         "client"
414                 };
415             }
416         };
417         SSLContext sc = SSLContext.getInstance("TLS");
418         sc.init(new KeyManager[] {
419                 km
420         }, null, null);
421         if (connection instanceof HttpsURLConnection) {
422             ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
423         }
424     }
425
426     public static String getCSRF(URLConnection u) throws IOException {
427         return getCSRF(u, 0);
428     }
429
430     public static String getCSRF(URLConnection u, int formIndex) throws IOException {
431         String content = IOUtils.readURL(u);
432         return getCSRF(formIndex, content);
433     }
434
435     public static String getCSRF(int formIndex, String content) throws Error {
436         Pattern p = Pattern.compile("<input type='hidden' name='csrf' value='([^']+)'>");
437         Matcher m = p.matcher(content);
438         for (int i = 0; i < formIndex + 1; i++) {
439             if ( !m.find()) {
440                 throw new Error("No CSRF Token:\n" + content);
441             }
442         }
443         return m.group(1);
444     }
445
446     public static String executeBasicWebInteraction(String cookie, String path, String query) throws MalformedURLException, UnsupportedEncodingException, IOException {
447         return executeBasicWebInteraction(cookie, path, query, 0);
448     }
449
450     public static String executeBasicWebInteraction(String cookie, String path, String query, int formIndex) throws IOException, MalformedURLException, UnsupportedEncodingException {
451         HttpURLConnection uc = post(cookie, path, query, formIndex);
452         if (uc.getResponseCode() == 302) {
453             return null;
454         }
455         String error = fetchStartErrorMessage(IOUtils.readURL(uc));
456         return error;
457     }
458
459     public static HttpURLConnection post(String cookie, String path, String query, int formIndex) throws IOException, MalformedURLException, UnsupportedEncodingException {
460         URLConnection uc = new URL("https://" + getServerName() + path).openConnection();
461         uc.addRequestProperty("Cookie", cookie);
462         String csrf = getCSRF(uc, formIndex);
463
464         uc = new URL("https://" + getServerName() + path).openConnection();
465         uc.addRequestProperty("Cookie", cookie);
466         uc.setDoOutput(true);
467         OutputStream os = uc.getOutputStream();
468         os.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" //
469                 + query//
470         ).getBytes("UTF-8"));
471         os.flush();
472         return (HttpURLConnection) uc;
473     }
474
475     public static HttpURLConnection get(String cookie, String path) throws IOException {
476         URLConnection uc = new URL("https://" + getServerName() + path).openConnection();
477         uc.addRequestProperty("Cookie", cookie);
478         return (HttpURLConnection) uc;
479     }
480
481     public EmailAddress createVerifiedEmail(User u) throws InterruptedException, GigiApiException {
482         return createVerifiedEmail(u, createUniqueName() + "test@test.tld");
483     }
484
485     public EmailAddress createVerifiedEmail(User u, String email) throws InterruptedException, GigiApiException {
486         EmailAddress addr = new EmailAddress(u, email, Locale.ENGLISH);
487         TestMail testMail = getMailReceiver().receive();
488         assertEquals(addr.getAddress(), testMail.getTo());
489         String hash = testMail.extractLink().substring(testMail.extractLink().lastIndexOf('=') + 1);
490         addr.verify(hash);
491         getMailReceiver().clearMails();
492         return addr;
493     }
494
495     public static URLConnection cookie(URLConnection openConnection, String cookie) {
496         openConnection.setRequestProperty("Cookie", cookie);
497         return openConnection;
498     }
499
500     private static User supporter;
501
502     public static User getSupporter() throws GigiApiException, IOException {
503         if (supporter != null) {
504             return supporter;
505         }
506         int i = createVerifiedUser("fn", "ln", createUniqueName() + "@email.com", TEST_PASSWORD);
507         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
508             ps.setInt(1, i);
509             ps.setString(2, Group.SUPPORTER.getDBName());
510             ps.setInt(3, i);
511             ps.execute();
512         }
513         clearCaches();
514         supporter = User.getById(i);
515         return supporter;
516     }
517 }