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