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