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