1 package org.cacert.gigi.testUtils;
3 import static org.junit.Assert.assertEquals;
4 import static org.junit.Assert.assertNotEquals;
5 import static org.junit.Assert.assertTrue;
7 import java.io.BufferedReader;
8 import java.io.DataOutputStream;
9 import java.io.FileInputStream;
10 import java.io.IOException;
11 import java.io.InputStreamReader;
12 import java.io.OutputStream;
13 import java.io.UnsupportedEncodingException;
14 import java.net.HttpURLConnection;
15 import java.net.InetSocketAddress;
16 import java.net.MalformedURLException;
17 import java.net.Socket;
19 import java.net.URLConnection;
20 import java.net.URLEncoder;
21 import java.nio.file.Files;
22 import java.nio.file.Paths;
23 import java.security.KeyManagementException;
24 import java.security.NoSuchAlgorithmException;
25 import java.security.Principal;
26 import java.security.PrivateKey;
27 import java.security.cert.X509Certificate;
28 import java.sql.PreparedStatement;
29 import java.sql.ResultSet;
30 import java.sql.SQLException;
31 import java.util.Properties;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
35 import javax.net.ssl.HttpsURLConnection;
36 import javax.net.ssl.KeyManager;
37 import javax.net.ssl.SSLContext;
38 import javax.net.ssl.X509KeyManager;
40 import org.cacert.gigi.DevelLauncher;
41 import org.cacert.gigi.database.DatabaseConnection;
42 import org.cacert.gigi.testUtils.TestEmailReciever.TestMail;
43 import org.cacert.gigi.util.DatabaseManager;
44 import org.cacert.gigi.util.SimpleSigner;
45 import org.junit.After;
46 import org.junit.AfterClass;
47 import org.junit.BeforeClass;
49 public class ManagedTest {
50 private final String registerService = "/register";
52 private static TestEmailReciever ter;
53 private static Process gigi;
54 private static String url = "localhost:4443";
56 public static String getServerName() {
60 static Properties testProps = new Properties();
63 HttpURLConnection.setFollowRedirects(false);
67 public static void connectToServer() {
69 testProps.load(new FileInputStream("config/test.properties"));
70 if (!DatabaseConnection.isInited()) {
71 DatabaseConnection.init(testProps);
73 System.out.println("... purging Database");
74 DatabaseManager.run(new String[] { testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"),
75 testProps.getProperty("sql.user"), testProps.getProperty("sql.password") });
77 String type = testProps.getProperty("type");
78 if (type.equals("local")) {
79 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
80 String[] parts = testProps.getProperty("mail").split(":", 2);
81 ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
84 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
85 gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
86 DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
87 System.out.println("... starting server");
88 Properties mainProps = new Properties();
89 mainProps.setProperty("host", "127.0.0.1");
90 mainProps.setProperty("name.secure", testProps.getProperty("name.secure"));
91 mainProps.setProperty("name.www", testProps.getProperty("name.www"));
92 mainProps.setProperty("name.static", testProps.getProperty("name.static"));
94 mainProps.setProperty("port", testProps.getProperty("serverPort"));
95 mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider");
96 mainProps.setProperty("emailProvider.port", "8473");
97 mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
98 mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
99 mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
100 mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
102 byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
103 byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
105 DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts,
109 final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream()));
111 while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) {
118 while ((line = br.readLine()) != null) {
119 System.err.println(line);
121 } catch (IOException e) {
127 throw new Error("Server startup failed");
129 ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473));
130 SimpleSigner.runSigner();
131 } catch (IOException e) {
133 } catch (ClassNotFoundException e1) {
134 e1.printStackTrace();
135 } catch (SQLException e1) {
136 e1.printStackTrace();
137 } catch (InterruptedException e) {
144 public static void tearDownServer() {
145 String type = testProps.getProperty("type");
147 if (type.equals("local")) {
152 SimpleSigner.stopSigner();
153 } catch (InterruptedException e) {
159 public void removeMails() {
163 public TestMail waitForMail() {
165 return ter.recieve();
166 } catch (InterruptedException e) {
171 public static TestEmailReciever getMailReciever() {
175 public String runRegister(String param) throws IOException {
176 URL regist = new URL("https://" + getServerName() + registerService);
177 HttpURLConnection uc = (HttpURLConnection) regist.openConnection();
178 HttpURLConnection csrfConn = (HttpURLConnection) regist.openConnection();
180 String headerField = csrfConn.getHeaderField("Set-Cookie");
181 headerField = stripCookie(headerField);
183 String csrf = getCSRF(csrfConn);
184 uc.addRequestProperty("Cookie", headerField);
185 uc.setDoOutput(true);
186 uc.getOutputStream().write((param + "&csrf=" + csrf).getBytes());
187 String d = IOUtils.readURL(uc);
191 public String fetchStartErrorMessage(String d) throws IOException {
192 String formFail = "<div class='formError'>";
193 int idx = d.indexOf(formFail);
194 assertNotEquals(-1, idx);
195 String startError = d.substring(idx + formFail.length(), idx + 100).trim();
199 public void registerUser(String firstName, String lastName, String email, String password) {
201 String query = "fname=" + URLEncoder.encode(firstName, "UTF-8") + "&lname="
202 + URLEncoder.encode(lastName, "UTF-8") + "&email=" + URLEncoder.encode(email, "UTF-8") + "&pword1="
203 + URLEncoder.encode(password, "UTF-8") + "&pword2=" + URLEncoder.encode(password, "UTF-8")
204 + "&day=1&month=1&year=1910&cca_agree=1";
205 String data = fetchStartErrorMessage(runRegister(query));
206 assertTrue(data, data.startsWith("</div>"));
207 } catch (UnsupportedEncodingException e) {
209 } catch (IOException e) {
214 public int createVerifiedUser(String firstName, String lastName, String email, String password) {
215 registerUser(firstName, lastName, email, password);
217 TestMail tm = ter.recieve();
218 String verifyLink = tm.extractLink();
219 String[] parts = verifyLink.split("\\?");
220 URL u = new URL("https://" + getServerName() + "/verify?" + parts[1]);
221 u.openStream().close();
223 PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM users where email=?");
224 ps.setString(1, email);
225 ResultSet rs = ps.executeQuery();
230 } catch (InterruptedException e) {
232 } catch (IOException e) {
234 } catch (SQLException e) {
240 * Creates a new user with 100 Assurance points given by an (invalid)
251 * @return a new userid.
253 public int createAssuranceUser(String firstName, String lastName, String email, String password) {
254 int uid = createVerifiedUser(firstName, lastName, email, password);
256 PreparedStatement ps = DatabaseConnection.getInstance().prepare(
257 "INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
261 ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
266 } catch (SQLException e) {
272 static int count = 0;
274 public String createUniqueName() {
275 return "test" + System.currentTimeMillis() + "a" + (count++);
278 private String stripCookie(String headerField) {
279 return headerField.substring(0, headerField.indexOf(';'));
282 public static final String SECURE_REFERENCE = "/account/certs/email";
284 public boolean isLoggedin(String cookie) throws IOException {
285 URL u = new URL("https://" + getServerName() + SECURE_REFERENCE);
286 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
287 huc.addRequestProperty("Cookie", cookie);
288 return huc.getResponseCode() == 200;
291 public String login(String email, String pw) throws IOException {
292 URL u = new URL("https://" + getServerName() + "/login");
293 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
294 huc.setDoOutput(true);
295 OutputStream os = huc.getOutputStream();
296 String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8");
297 os.write(data.getBytes());
299 String headerField = huc.getHeaderField("Set-Cookie");
300 return stripCookie(headerField);
303 public String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException,
304 KeyManagementException, IOException, MalformedURLException {
306 HttpURLConnection connection = (HttpURLConnection) new URL("https://"
307 + getServerName().replaceFirst("^www.", "secure.") + "/login").openConnection();
308 authenticateClientCert(pk, ce, connection);
309 if (connection.getResponseCode() == 302) {
310 assertEquals("https://" + getServerName().replaceFirst("^www.", "secure.").replaceFirst(":443$", "") + "/",
311 connection.getHeaderField("Location").replaceFirst(":443$", ""));
312 return stripCookie(connection.getHeaderField("Set-Cookie"));
318 public void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection)
319 throws NoSuchAlgorithmException, KeyManagementException {
320 KeyManager km = new X509KeyManager() {
323 public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
328 public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
333 public X509Certificate[] getCertificateChain(String arg0) {
334 return new X509Certificate[] { ce };
338 public String[] getClientAliases(String arg0, Principal[] arg1) {
339 return new String[] { "client" };
343 public PrivateKey getPrivateKey(String arg0) {
344 if (arg0.equals("client")) {
351 public String[] getServerAliases(String arg0, Principal[] arg1) {
352 return new String[] { "client" };
355 SSLContext sc = SSLContext.getInstance("TLS");
356 sc.init(new KeyManager[] { km }, null, null);
357 if (connection instanceof HttpsURLConnection) {
358 ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
362 public String getCSRF(URLConnection u) throws IOException {
363 String content = IOUtils.readURL(u);
364 Pattern p = Pattern.compile("<input type='hidden' name='csrf' value='([^']+)'>");
365 Matcher m = p.matcher(content);
367 throw new Error("No CSRF Token");
372 public static String[] generateCSR(String dn) throws IOException {
373 Process p = Runtime.getRuntime().exec(
374 new String[] { "openssl", "req", "-newkey", "rsa:1024", "-nodes", "-subj", dn, "-config",
375 "keys/selfsign.config" });
376 String csr = IOUtils.readURL(new InputStreamReader(p.getInputStream()));
378 String[] parts = csr.split("(?<=-----)\n(?=-----)");
379 if (parts.length != 2) {
380 System.err.println(IOUtils.readURL(new InputStreamReader(p.getErrorStream())));