1 package org.cacert.gigi.testUtils;
3 import static org.junit.Assert.*;
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;
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;
37 import javax.net.ssl.HttpsURLConnection;
38 import javax.net.ssl.KeyManager;
39 import javax.net.ssl.SSLContext;
40 import javax.net.ssl.X509KeyManager;
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;
59 import sun.security.pkcs10.PKCS10;
60 import sun.security.pkcs10.PKCS10Attributes;
61 import sun.security.x509.X500Name;
63 public class ManagedTest {
66 * Some password that fullfills the password criteria.
68 protected static final String TEST_PASSWORD = "xvXV12°§";
70 private static TestEmailReciever ter;
72 private static Process gigi;
74 private static String url = "localhost:4443";
76 public static String getServerName() {
80 static Properties testProps = new Properties();
82 public static Properties getTestProps() {
88 HttpURLConnection.setFollowRedirects(false);
92 public static void connectToServer() {
94 testProps.load(new FileInputStream("config/test.properties"));
95 if ( !DatabaseConnection.isInited()) {
96 DatabaseConnection.init(testProps);
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")
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.https");
107 String[] parts = testProps.getProperty("mail").split(":", 2);
108 ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
111 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort.https");
112 gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
113 DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
114 System.out.println("... starting server");
116 byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
117 byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
119 DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts, keystore);
122 final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream()));
124 while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) {
132 while ((line = br.readLine()) != null) {
133 System.err.println(line);
135 } catch (IOException e) {
141 throw new Error("Server startup failed");
143 ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473));
144 SimpleSigner.runSigner();
145 } catch (IOException e) {
147 } catch (ClassNotFoundException e1) {
148 e1.printStackTrace();
149 } catch (SQLException e1) {
150 e1.printStackTrace();
151 } catch (InterruptedException e) {
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"));
164 mainProps.setProperty("https.port", testProps.getProperty("serverPort.https"));
165 mainProps.setProperty("http.port", testProps.getProperty("serverPort.http"));
166 mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider");
167 mainProps.setProperty("emailProvider.port", "8473");
168 mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
169 mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
170 mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
171 mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
176 public static void tearDownServer() {
177 String type = testProps.getProperty("type");
179 if (type.equals("local")) {
184 SimpleSigner.stopSigner();
185 } catch (InterruptedException e) {
190 public final String uniq = createUniqueName();
193 public void removeMails() {
197 public TestMail waitForMail() {
199 return ter.recieve();
200 } catch (InterruptedException e) {
205 public static TestEmailReciever getMailReciever() {
209 public static String runRegister(String param) throws IOException {
210 URL regist = new URL("https://" + getServerName() + RegisterPage.PATH);
211 HttpURLConnection uc = (HttpURLConnection) regist.openConnection();
212 HttpURLConnection csrfConn = (HttpURLConnection) regist.openConnection();
214 String headerField = csrfConn.getHeaderField("Set-Cookie");
215 headerField = stripCookie(headerField);
217 String csrf = getCSRF(csrfConn);
218 uc.addRequestProperty("Cookie", headerField);
219 uc.setDoOutput(true);
220 uc.getOutputStream().write((param + "&csrf=" + csrf).getBytes());
221 String d = IOUtils.readURL(uc);
225 public static String fetchStartErrorMessage(String d) throws IOException {
226 String formFail = "<div class='formError'>";
227 int idx = d.indexOf(formFail);
231 String startError = d.substring(idx + formFail.length(), idx + 100).trim();
235 public static void registerUser(String firstName, String lastName, String email, String password) {
237 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";
238 String data = fetchStartErrorMessage(runRegister(query));
240 } catch (UnsupportedEncodingException e) {
242 } catch (IOException e) {
247 public static int createVerifiedUser(String firstName, String lastName, String email, String password) {
248 registerUser(firstName, lastName, email, password);
250 TestMail tm = ter.recieve();
251 String verifyLink = tm.extractLink();
252 String[] parts = verifyLink.split("\\?");
253 URL u = new URL("https://" + getServerName() + "/verify?" + parts[1]);
254 u.openStream().close();
256 PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM users where email=?");
257 ps.setString(1, email);
258 ResultSet rs = ps.executeQuery();
263 } catch (InterruptedException e) {
265 } catch (IOException e) {
267 } catch (SQLException e) {
273 * Creates a new user with 100 Assurance points given by an (invalid)
284 * @return a new userid.
286 public static int createAssuranceUser(String firstName, String lastName, String email, String password) {
287 int uid = createVerifiedUser(firstName, lastName, email, password);
289 PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
293 ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
298 } catch (SQLException e) {
304 static int count = 0;
306 public static String createUniqueName() {
307 return "test" + System.currentTimeMillis() + "a" + (count++) + "u";
310 private static String stripCookie(String headerField) {
311 return headerField.substring(0, headerField.indexOf(';'));
314 public static final String SECURE_REFERENCE = MyDetails.PATH;
316 public static boolean isLoggedin(String cookie) throws IOException {
317 URL u = new URL("https://" + getServerName() + SECURE_REFERENCE);
318 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
319 huc.addRequestProperty("Cookie", cookie);
320 return huc.getResponseCode() == 200;
323 public static String login(String email, String pw) throws IOException {
324 URL u = new URL("https://" + getServerName() + "/login");
325 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
326 huc.setDoOutput(true);
327 OutputStream os = huc.getOutputStream();
328 String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8");
329 os.write(data.getBytes());
331 String headerField = huc.getHeaderField("Set-Cookie");
332 return stripCookie(headerField);
335 public static String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException, KeyManagementException, IOException, MalformedURLException {
337 HttpURLConnection connection = (HttpURLConnection) new URL("https://" + getServerName().replaceFirst("^www.", "secure.") + "/login").openConnection();
338 authenticateClientCert(pk, ce, connection);
339 if (connection.getResponseCode() == 302) {
340 assertEquals("https://" + getServerName().replaceFirst("^www.", "secure.").replaceFirst(":443$", "") + "/", connection.getHeaderField("Location").replaceFirst(":443$", ""));
341 return stripCookie(connection.getHeaderField("Set-Cookie"));
347 public static void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {
348 KeyManager km = new X509KeyManager() {
351 public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
356 public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
361 public X509Certificate[] getCertificateChain(String arg0) {
362 return new X509Certificate[] {
368 public String[] getClientAliases(String arg0, Principal[] arg1) {
369 return new String[] {
375 public PrivateKey getPrivateKey(String arg0) {
376 if (arg0.equals("client")) {
383 public String[] getServerAliases(String arg0, Principal[] arg1) {
384 return new String[] {
389 SSLContext sc = SSLContext.getInstance("TLS");
390 sc.init(new KeyManager[] {
393 if (connection instanceof HttpsURLConnection) {
394 ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
398 public static String getCSRF(URLConnection u) throws IOException {
399 return getCSRF(u, 0);
402 public static String getCSRF(URLConnection u, int formIndex) throws IOException {
403 String content = IOUtils.readURL(u);
404 return getCSRF(formIndex, content);
407 public static String getCSRF(int formIndex, String content) throws Error {
408 Pattern p = Pattern.compile("<input type='hidden' name='csrf' value='([^']+)'>");
409 Matcher m = p.matcher(content);
410 for (int i = 0; i < formIndex + 1; i++) {
412 throw new Error("No CSRF Token");
418 public static KeyPair generateKeypair() throws GeneralSecurityException {
419 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
420 kpg.initialize(4096);
421 return kpg.generateKeyPair();
424 public static String generatePEMCSR(KeyPair kp, String dn) throws GeneralSecurityException, IOException {
425 return generatePEMCSR(kp, dn, new PKCS10Attributes());
428 public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts) throws GeneralSecurityException, IOException {
429 return generatePEMCSR(kp, dn, atts, "SHA256WithRSA");
432 public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts, String signature) throws GeneralSecurityException, IOException {
433 PKCS10 p10 = new PKCS10(kp.getPublic(), atts);
434 Signature s = Signature.getInstance(signature);
435 s.initSign(kp.getPrivate());
436 p10.encodeAndSign(new X500Name(dn), s);
437 return PEM.encode("CERTIFICATE REQUEST", p10.getEncoded());
440 public static String executeBasicWebInteraction(String cookie, String path, String query) throws MalformedURLException, UnsupportedEncodingException, IOException {
441 return executeBasicWebInteraction(cookie, path, query, 0);
444 public static String executeBasicWebInteraction(String cookie, String path, String query, int formIndex) throws IOException, MalformedURLException, UnsupportedEncodingException {
445 URLConnection uc = new URL("https://" + getServerName() + path).openConnection();
446 uc.addRequestProperty("Cookie", cookie);
447 String csrf = getCSRF(uc, formIndex);
449 uc = new URL("https://" + getServerName() + path).openConnection();
450 uc.addRequestProperty("Cookie", cookie);
451 uc.setDoOutput(true);
452 OutputStream os = uc.getOutputStream();
453 os.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" //
457 String error = fetchStartErrorMessage(IOUtils.readURL(uc));
461 public static EmailAddress createVerifiedEmail(User u) throws InterruptedException, GigiApiException {
462 EmailAddress adrr = new EmailAddress(createUniqueName() + "test@test.tld", u);
463 adrr.insert(Language.getInstance("en"));
464 TestMail testMail = getMailReciever().recieve();
465 assertTrue(adrr.getAddress().equals(testMail.getTo()));
466 String hash = testMail.extractLink().substring(testMail.extractLink().lastIndexOf('=') + 1);
468 getMailReciever().clearMails();
472 public static URLConnection cookie(URLConnection openConnection, String cookie) {
473 openConnection.setRequestProperty("Cookie", cookie);
474 return openConnection;