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