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