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