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