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 {
51 * Some password that fullfills the password criteria.
53 protected static final String TEST_PASSWORD = "xvXV12°§";
55 private final String registerService = "/register";
57 private static TestEmailReciever ter;
58 private static Process gigi;
59 private static String url = "localhost:4443";
61 public static String getServerName() {
65 static Properties testProps = new Properties();
68 HttpURLConnection.setFollowRedirects(false);
72 public static void connectToServer() {
74 testProps.load(new FileInputStream("config/test.properties"));
75 if (!DatabaseConnection.isInited()) {
76 DatabaseConnection.init(testProps);
78 System.out.println("... purging Database");
79 DatabaseManager.run(new String[] { testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"),
80 testProps.getProperty("sql.user"), testProps.getProperty("sql.password") });
82 String type = testProps.getProperty("type");
83 if (type.equals("local")) {
84 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
85 String[] parts = testProps.getProperty("mail").split(":", 2);
86 ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
89 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
90 gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
91 DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
92 System.out.println("... starting server");
93 Properties mainProps = new Properties();
94 mainProps.setProperty("host", "127.0.0.1");
95 mainProps.setProperty("name.secure", testProps.getProperty("name.secure"));
96 mainProps.setProperty("name.www", testProps.getProperty("name.www"));
97 mainProps.setProperty("name.static", testProps.getProperty("name.static"));
99 mainProps.setProperty("port", testProps.getProperty("serverPort"));
100 mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider");
101 mainProps.setProperty("emailProvider.port", "8473");
102 mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
103 mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
104 mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
105 mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
107 byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
108 byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
110 DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts,
114 final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream()));
116 while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) {
123 while ((line = br.readLine()) != null) {
124 System.err.println(line);
126 } catch (IOException e) {
132 throw new Error("Server startup failed");
134 ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473));
135 SimpleSigner.runSigner();
136 } catch (IOException e) {
138 } catch (ClassNotFoundException e1) {
139 e1.printStackTrace();
140 } catch (SQLException e1) {
141 e1.printStackTrace();
142 } catch (InterruptedException e) {
149 public static void tearDownServer() {
150 String type = testProps.getProperty("type");
152 if (type.equals("local")) {
157 SimpleSigner.stopSigner();
158 } catch (InterruptedException e) {
164 public void removeMails() {
168 public TestMail waitForMail() {
170 return ter.recieve();
171 } catch (InterruptedException e) {
176 public static TestEmailReciever getMailReciever() {
180 public String runRegister(String param) throws IOException {
181 URL regist = new URL("https://" + getServerName() + registerService);
182 HttpURLConnection uc = (HttpURLConnection) regist.openConnection();
183 HttpURLConnection csrfConn = (HttpURLConnection) regist.openConnection();
185 String headerField = csrfConn.getHeaderField("Set-Cookie");
186 headerField = stripCookie(headerField);
188 String csrf = getCSRF(csrfConn);
189 uc.addRequestProperty("Cookie", headerField);
190 uc.setDoOutput(true);
191 uc.getOutputStream().write((param + "&csrf=" + csrf).getBytes());
192 String d = IOUtils.readURL(uc);
196 public String fetchStartErrorMessage(String d) throws IOException {
197 String formFail = "<div class='formError'>";
198 int idx = d.indexOf(formFail);
199 assertNotEquals(-1, idx);
200 String startError = d.substring(idx + formFail.length(), idx + 100).trim();
204 public void registerUser(String firstName, String lastName, String email, String password) {
206 String query = "fname=" + URLEncoder.encode(firstName, "UTF-8") + "&lname="
207 + URLEncoder.encode(lastName, "UTF-8") + "&email=" + URLEncoder.encode(email, "UTF-8") + "&pword1="
208 + URLEncoder.encode(password, "UTF-8") + "&pword2=" + URLEncoder.encode(password, "UTF-8")
209 + "&day=1&month=1&year=1910&cca_agree=1";
210 String data = fetchStartErrorMessage(runRegister(query));
211 assertTrue(data, data.startsWith("</div>"));
212 } catch (UnsupportedEncodingException e) {
214 } catch (IOException e) {
219 public int createVerifiedUser(String firstName, String lastName, String email, String password) {
220 registerUser(firstName, lastName, email, password);
222 TestMail tm = ter.recieve();
223 String verifyLink = tm.extractLink();
224 String[] parts = verifyLink.split("\\?");
225 URL u = new URL("https://" + getServerName() + "/verify?" + parts[1]);
226 u.openStream().close();
228 PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM users where email=?");
229 ps.setString(1, email);
230 ResultSet rs = ps.executeQuery();
235 } catch (InterruptedException e) {
237 } catch (IOException e) {
239 } catch (SQLException e) {
245 * Creates a new user with 100 Assurance points given by an (invalid)
256 * @return a new userid.
258 public int createAssuranceUser(String firstName, String lastName, String email, String password) {
259 int uid = createVerifiedUser(firstName, lastName, email, password);
261 PreparedStatement ps = DatabaseConnection.getInstance().prepare(
262 "INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
266 ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
271 } catch (SQLException e) {
277 static int count = 0;
279 public String createUniqueName() {
280 return "test" + System.currentTimeMillis() + "a" + (count++);
283 private String stripCookie(String headerField) {
284 return headerField.substring(0, headerField.indexOf(';'));
287 public static final String SECURE_REFERENCE = "/account/certs/email";
289 public boolean isLoggedin(String cookie) throws IOException {
290 URL u = new URL("https://" + getServerName() + SECURE_REFERENCE);
291 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
292 huc.addRequestProperty("Cookie", cookie);
293 return huc.getResponseCode() == 200;
296 public String login(String email, String pw) throws IOException {
297 URL u = new URL("https://" + getServerName() + "/login");
298 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
299 huc.setDoOutput(true);
300 OutputStream os = huc.getOutputStream();
301 String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8");
302 os.write(data.getBytes());
304 String headerField = huc.getHeaderField("Set-Cookie");
305 return stripCookie(headerField);
308 public String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException,
309 KeyManagementException, IOException, MalformedURLException {
311 HttpURLConnection connection = (HttpURLConnection) new URL("https://"
312 + getServerName().replaceFirst("^www.", "secure.") + "/login").openConnection();
313 authenticateClientCert(pk, ce, connection);
314 if (connection.getResponseCode() == 302) {
315 assertEquals("https://" + getServerName().replaceFirst("^www.", "secure.").replaceFirst(":443$", "") + "/",
316 connection.getHeaderField("Location").replaceFirst(":443$", ""));
317 return stripCookie(connection.getHeaderField("Set-Cookie"));
323 public void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection)
324 throws NoSuchAlgorithmException, KeyManagementException {
325 KeyManager km = new X509KeyManager() {
328 public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
333 public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
338 public X509Certificate[] getCertificateChain(String arg0) {
339 return new X509Certificate[] { ce };
343 public String[] getClientAliases(String arg0, Principal[] arg1) {
344 return new String[] { "client" };
348 public PrivateKey getPrivateKey(String arg0) {
349 if (arg0.equals("client")) {
356 public String[] getServerAliases(String arg0, Principal[] arg1) {
357 return new String[] { "client" };
360 SSLContext sc = SSLContext.getInstance("TLS");
361 sc.init(new KeyManager[] { km }, null, null);
362 if (connection instanceof HttpsURLConnection) {
363 ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
367 public String getCSRF(URLConnection u) throws IOException {
368 String content = IOUtils.readURL(u);
369 Pattern p = Pattern.compile("<input type='hidden' name='csrf' value='([^']+)'>");
370 Matcher m = p.matcher(content);
372 throw new Error("No CSRF Token");
377 public static String[] generateCSR(String dn) throws IOException {
378 Process p = Runtime.getRuntime().exec(
379 new String[] { "openssl", "req", "-newkey", "rsa:1024", "-nodes", "-subj", dn, "-config",
380 "keys/selfsign.config" });
381 String csr = IOUtils.readURL(new InputStreamReader(p.getInputStream()));
383 String[] parts = csr.split("(?<=-----)\n(?=-----)");
384 if (parts.length != 2) {
385 System.err.println(IOUtils.readURL(new InputStreamReader(p.getErrorStream())));