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