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