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