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